How to identify a google map marker on click? - google-maps

I'm creating a Google Map from the developer API v3. It's populated with markers created dynamically from ColdFusion querying an MsSQL database.
<cfloop query="One">
<script>locations[<cfoutput>#One.userID#</cfoutput>
] = new google.maps.LatLng(<cfoutput>#One.latLng#</cfoutput>);
</script>
</cfloop>
I need a way to recognise the marker when its clicked so I can display address details in a box below the map and also higlight markers when a button is clicked lower on the page.

In general, you would typically assign your own custom properties to the Marker. Something like:
function markerClicked(e) {
console.log('Marker ' + marker.myData + ' has been clicked');
}
var marker = new google.maps.Marker(...);
marker.myData = 1; //this could be arbitrary data or even another object
google.maps.event.addListener(marker, 'click', markerClicked);
Adding custom data to any Google Maps API object has risks though. Google's code is obfuscated and the internal (non-documented) properties can and do change. Make sure your property is named in such a way that it won't conflict with any existing property or future property. Tip: Choose a property name longer than 3 letters.
If you are going to minify/compile/compress your maps code, then there are additional considerations.

What about :
google.maps.event.addListener(marker, "click", function (e) {
var clicked = this;
//...
});

This is pretty thoroughly documented/explained in the documentation.
https://developers.google.com/maps/documentation/javascript/overlays#InfoWindows
When you create markers, add dom listeners to the markers like this
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});

Related

Adding click handler to geojson in maps API

Is there a way to associate a GeoJson with a click event?
const features = map.data.addGeoJson(json);
for (const feature of features) {
// Add styling
map.data.overrideStyle(
feature,{
fillColor: 'red',
});
// TODO: Add a click handler for "feature"
}
For normal entities, such as LatLngBounds, there seems to be addListener(instance, eventName, handler). This does however not exist for the feature from the snippet above.
Is there an equivalent alternative for geojson features?
Nevermind, I just found this help page, which gives a snippet on how to do this:
// Set mouseover event for each feature.
map.data.addListener('mouseover', function(event) {
// "event" has the feature as a property.
document.getElementById('info-box').textContent =
event.feature.getProperty('letter');
});

Backbone Marionette Google Maps infowindow button event

I know how to display an infoWindow, but I have a problem capturing the event from a button displayed there.
var view = Marionette.LayoutView.extend({
...
methodA: function(){
me.showMapInfoWindow(marker, "Test popup<button onclick='methodB()'>Click me</button>")
me.infoWindow.open(me.map, marker);
},
methodB: function(){
console.log("test");
}
}
When I click the button, I get an error when calling methodB saying it's not defined. I've tried with me.methodB, etc...but no luck there. How can I fix this?
Here is a JSFiddle showing an InfoWindow populated with a DOM node, rather than a HTML string. This way, we can use jQuery to add a programmatic event to the DOM, which can access the current scope, as shown.
var $infoWindow = $('<div>Test popup<button>Click me</button></div>');
$infoWindow.find('button').click(_.bind(this.methodB, this));
me.showMapInfoWindow(marker, $infoWindow.get(0));
me.infoWindow.open(me.map, marker);
Answer to First Question
Here is a JSFiddle showing an InfoWindow firing a global function. In this case I had to set the function to Window scope, though I believe this is due to the JSFiddle environment.
window.myFunction = function() {
window.alert("function fired!");
}
...
var html = '<button onclick=\'myFunction()\'>Click me</button>';
if you want to debug the scope, I'd suggest using the debugger statement:
var html = '<button onclick=\'debugger;\'>Click me</button>';

Imitating Mouse click - point with known coordinates on a fusion table layer - google maps

I have been making a script using a fusion table's layer in google maps.
I am using geocoder and get the coordinates of a point that I need.
I put a script that changes the style of a polygon from the fusion table when you click on it, using the google.maps.event.addListener(layer, "click", function(e) {});
I would like to use the same function that I call in the case of a click on the layer, but this time with a click with the coordinates that I got.
I have tried google.maps.event.trigger(map, 'click', {latLng: new google.maps.LatLng(42.701487,26.772308)});
As well as the example here > Google Fusion Table Double Click (dblClick)
I have tried changing map with layer...
I am sorry if my question is quite stupid, but I have tried many options.
P.S. I have seen many post about getting the info from the table, but I do not need that. I want to change the style of the KML element in the selected row, so I do not see it happening by a query.
Here is the model of my script:
function initialize()
{
geocoder = new google.maps.Geocoder();
map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
layer = new google.maps.FusionTablesLayer({
suppressInfoWindows:true,
map : map,
query : {
select: 'Местоположение',
from: '12ZoroPjIfBR4J-XwM6Rex7LmfhzCDJc9_vyG5SM'
}
});
google.maps.event.addListener(layer, "click", function(e) {
SmeniStilRaionni(layer,e);
marker.setMap(null);
});
}
function SmeniStilRaionni(layer,e)
{
...
}
function showAddress(address)
{
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var point = results[0].geometry.location;
//IMITATE THE CLICK
}
});
}
In response to geocodezip
This way you hide all the other elements... I do not wish that. It is like if I want to change the border of the selected element. And I do not wish for a new layer.
In the function that I use now I push the style of the options of the layer and then set the option. I use the e from google.maps.event.addListener(layer, "click", function(e)); by inserting e.row['Name'].value inside the where rule.
I would like to ask you if there is any info on the e variable in google.maps.event.addListener(layer, "click", function(e));
I found out how to get the results I wanted:
For my query after I get the point I use this:
var queryText ="SELECT 'Районен съд','Окръжен съд','Апелативен съд','Местоположение' FROM "+FusionTableID+" WHERE ST_INTERSECTS(\'Местоположение\', CIRCLE(LATLNG(" + point.toUrlValue(6) + "),0.5));";
queryText = encodeURIComponent(queryText);
document.getElementById("vij query").innerHTML = queryText;
var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + queryText);
And then I get these results:
var rsyd = response.getDataTable().getValue(0,0);
var osyd = response.getDataTable().getValue(0,1);
var apsyd = response.getDataTable().getValue(0,2);
And then, I use the following:
where: "'Районен съд' = '"+rsyd+"'",
Which is the same as:
where: "'Районен съд' = '"+e.row['Районен съд'].value+"'",
in the click function.
This is a working solution for my problem.
But still, I cannot find a way to Imitate a Mouse click.
The issue is this: the data(row) for the layers will be requested via AJAX when you click on a layer.
In theory it's possible to select a geometry(polygon) by a given LatLng, the geometry-library has a method for this: google.maps.geometry.poly.containsLocation().
Unfortunately the FusionTableAPI does not support such queries(ST_CONTAINS), you cannot select a row by supplying a LatLng and selecting the rows where the geometry contains the LatLng.
So what you can do: create a copy of the table that contains the columns needed to select a row(Община...the distinct value, and Местоположение.... the geometry). This copy may be requested via AJAX, but when the FusionTable will not be modified anymore I would suggest to use a hardcoded copy.
What to do now when you want to simulate the click:
Iterate over all rows of the copy, use the mentioned containsLocation()-method to check if the geometry(Местоположение) contains the LatLng and when it does apply the query by using the value of the distinct column Община .
Of course it would take some time to check all the geometries, but the FusionTable is not very large, it should be a possible approach in your case.
Here is a demo: http://jsfiddle.net/doktormolle/sSwj3/
The size of the stored data is approximately 500kb, you should store the data in an external script, so they may be cached.
You may notice that the highligthning of the selected layer will be much faster when triggered via the links, because there will no data be requested via AJAX. When the highlightning of the selected feature is the only thing you need you may ommit the observation of the layer-click completely and observe the map-click instead. Use the returned LatLng to retrieve the selected row from the data and set the style:
Demo: http://jsfiddle.net/doktormolle/swdX8/

Google Maps V3 Infobox undefined on polygons

I have a spoke in my wheels and I am not sure how to sort this out. I have been struggling with it for a couple days and it isn't like a normal infobox as it is not set to a marker rather a polygon which is something new for me. I have polygons that display with data from an XML file and they show up fine. I have searched the web and got it to have the mouseover set up to where you mouseover a polygon the opacity changes and an infobox pops up. Problem is the infobox when it pop up shows "undefined" instead of the html I have set in it to display with data from the XML file.
Here is a link to the test map for example.
http://www.mesquiteweather.net/googlemap_poly.html
Here is a link to the XML file where I am just trying to show the elements events and expires in the info box.
http://www.mesquiteweather.net/xml/warnings_test.xml
This is the code I am working with to create the infoboxes and mouseover events
function attachPolygonInfoWindow(polygon, html, event, expires)
{
var html = "<strong>" + event + "</strong>";
eventWarnings.infoWindow = new google.maps.InfoWindow({content: html});
google.maps.event.addListener(eventWarnings, 'mouseover', function(e) {
var latLng = e.latLng;
this.setOptions({fillOpacity:80});
polygon.infoWindow.setPosition(latLng);
polygon.infoWindow.open(map);
});
google.maps.event.addListener(eventWarnings, 'mouseout', function() {
this.setOptions({fillOpacity:0.35});
polygon.infoWindow.close();
});
}
var polygon = new google.maps.Polygon(/* omitted for brevity */);
attachPolygonInfoWindow(eventWarnings);
eventWarnings.setMap(map);
}
});
I am pretty sure it is something easy I am overlooking but I haven't been able to find anything that pertains to my issue. I am just lucky I got the infobox to show at all as I have learned it's tricky since polygons don't have a true center and they are not set up like you would with a marker which I can handle.
If anyone has any suggestions please let me know.
-Thanks
You defined your attachPolygonInfoWindow function with 4 argument, but only provide one when you call it:
// definition
function attachPolygonInfoWindow(polygon, html, event, expires)
...
// call
attachPolygonInfoWindow(eventWarnings);
Probably you want (I don't see the html or expires parameters being used):
attachPolygonInfoWindow(eventWarnings, "", event, null);
The other option would be to change the definition to:
// definition
function attachPolygonInfoWindow(polygon, event, expires)
and the call to (assuming you are going to use "expires" for something):
attachPolygonInfoWindow(eventWarnings, event, expires);
As it doesn't look like you need to pass in that parameter (event is serving the function that I would expect it to serve).
Also, FYI, you have a "hanging comma" in your alertColors.js which make IE unhappy...
example

overriding big popup on directions Google Maps

I've happily implemented v2 of Google maps to my site without a hitch, I also successfully perform a drive directions using GDirections.load().
What I need to do is stop the popup of the mini map when you select a particular step in the routing directions. So when the user clicks on say "step 3", instead of the default popup showing a mini map, I'd like to add a custom icon to that position.
Hope it makes sense
Thanks in advance guys.
You need to add a handler on the GDirections object for the addoverlay event:
GEvent.addListener(gdir, "addoverlay", onGDirectionsAddOverlay);
When your onGDirectionsAddOverlay handler is called you can iterate through the new markers and replace them with copies that open your custom info window:
for (var i = 0; i <= gdir.getNumRoutes(); i++)
{
var originalMarker = gdir.getMarker(i);
latLngs[i] = originalMarker.getLatLng();
icons[i] = originalMarker.getIcon();
newMarkers[i] = new GMarker(latLngs[i], { icon: icons[i], draggable: true, title: 'Kan flyttes' });
map.addOverlay(newMarkers[i]);
// add stuff to your newMarkers[i] click event...
// ..
// Now we can remove the original marker safely
map.removeOverlay(originalMarker);
}