How do I link Google Maps Markers to other elements? - javascript

Using the google maps (and JavaScript) I have been able to easily display several markers which each have a nice little info window over them.
//Create map over USA
map = new google.maps.Map2( document.getElementById('map') );
map.setCenter(new GLatLng(38.95940879245423, -100.283203125), 3);
//Create point, then marker, and then add to map
function create_marker(lat, lng, html) {
var marker = new GMarker( new GLatLng(lat,lng));
marker.bindInfoWindow(html);
map.addOverlay(marker);
}
var html = '<div>this is my text</div>';
create_marker(38.95940879245423, -100.283203125, html);
However, I now want to be able to link the "click" of markers to functions which can update other parts of the page as well. For example, I would like to have a sidebar with copies of the marker infowindow content. The same way google maps shows results on the left and markers on the right. I might even want the click of sidebar content to open a given marker infowindow on the map.
The problem is that the GMarker click event only passes the lat/long - and I'm not sure how I can use that to find the matching div or whatever.
How do I get a unique id/handle for each marker?

Assign an id to each marker and its corresponding element in the sidebar. Create an event listener to call that id. Something like this:
var html = '<div>this is my text</div>';
var sideHtml = '<div id="1">this is my text</div>';
create_marker(38.95940879245423, -100.283203125, html, 1);
$("#sidebar").append(sideHtml); // Add the text to the sidebar (jQuery)
//Create point, then marker, and then add to map
function create_marker(lat, lng, html, id) {
var marker = new GMarker( new GLatLng(lat,lng));
marker.bindInfoWindow(html);
map.addOverlay(marker);
GEvent.addListener(marker, 'click', function(latlng) {
var div = document.getElementById(id); //access the sidebar element
// etc...
});
}
See also this question.

For those interested there is a great example of linking dom elements with markers given here. Basically you just create a global JS array that holds a reference to each marker object.

Related

html marker add additional properties in azure maps

I am loading all sites of companies as a html markers in azure maps and on click of it, launch a popup that displays site specific information.
The Html marker does not have any property bag, through which i can pass a bunch of site information that i can use in the popup that i intent to display on click of html marker.
azure maps documentation on HtmlMarker: https://learn.microsoft.com/en-us/javascript/api/azure-maps-control/atlas.htmlmarkeroptions?view=azure-maps-typescript-latest
Any help?
Simple add a custom property to the html marker and add your data to that. That data will always be with the marker. For example:
var popup = new atlas.Popup();
//Create a HTML marker and add it to the map.
var marker = new atlas.HtmlMarker({
position: [0, 0]
});
//Add your custom property with data
marker.properties = {
title: 'hello world'
};
map.markers.add(marker);
map.events.add('click', marker, function(e){
//Get the clicked marker.
var m = e.target;
//Get custom properties on the marker
var p = m.properties;
popup.setOptions({
content: `<div style="padding:10px;">${p.title}</div>`,
position:m.getOptions().position,
pixelOffset: [0, -18]
});
//Open the popup.
popup.open(map);
});

Overwrite google.map with location

I have a main javascript file which generates a google map inside a div. This div is under many others which contains graphically visible datas needs for... somethgin similar to a dashboard. But on several other subpages I want to dynamically reload the map with unique parameters, but I can't according to the main map is listened on the load event. Not used the google map v3 api so much times so could anyone help me?
The main is generated by:
function mapInitialize() {
var mapOptions = {
zoom: 13,
styles: mapStyle
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
google.maps.event.addDomListener(window, 'load', mapInitialize);
In one of my subpage I want to generate a map with specific center, coordinates and a unique marker. So what I basically would do is to cal lagain the whole initialize() with my specific attributes, but it generates itself firstly then the one in main.js overwrite this already generated and wrong one :( How could I manage this easily, according to there are several subpages which should show this kind of unique datas after the page is fully loaded?
Google maps allows you to recenter the map after a map is already initialized:
var marker = new google.maps.Marker({
position: new google.maps.LatLng(latitude, longitude),
title: markerTitle,
map: map,
});
map.panTo(marker.getPosition());
Additionally, what keeps you from reinitializing the map whenever you want? Just because it is registered with an on load listener shouldn't prevent you from making new instances? (I think):
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

Google Maps API v3.0 Saving a reference to a marker

I am using Google Maps API v3.0
The map have MULTIPLE markers (so any examples of using 1 marker isnt what I am after)
Things are going ok so far.. but I am not clear on how you can save a reference to a specific marker when it is clicked? (which I have read as a suggestion few places, but no examples)
There are two separate instances where I would like to have a direct target/reference back to a specific marker to control/change the behavior/image..etc (whatever).
Example of scenario #1:
1.) When I click on a marker, I am currently 'bouncing it' as well as changing its icon to a different image. If I click on a new marker.. I want to target the OLD marker to stop bouncing/revert back to old icon. I have accomplished this by running a loop over my 'marker' array and stop all animations on all markers.. and changing all icons to the old (original) image. It works.. but I would like NOT to have the overhead of running through the loop. Going forward, I would like to change the old marker to a 3rd icon image.. (to show it has been interacted with before).. so I need a way to save/set a reference to a marker once it is clicked.. so I can target it again (directly)
Example of scenario #2:
1.) I have some 'controls' (elements) outside of the map, that I would like to use to interact with the map, as well as specific markers.
ie: Have an image of the marker/entry OUTSIDE of the map.. where a user clicks on it.. and it scrolls/pans the map to that specific marker (as well as changing animation and icon image)
Here is my current click listener:
google.maps.event.addListener(addr[n], 'click', (function(marker, n) {
return function() {
infowindow.setContent(addr[n].title + "<br />" + addr[n].company + "<br />" + addr[n].workphone);
infowindow.open(map, addr[n]);
//increase z-index when marker has focus
addr[n].setZIndex(google.maps.Marker.MAX_ZINDEX + 1);
}
})(marker, n));
Q:
How can I save a DIRECT reference to a marker on the map when it is clicked, to be used in another function and referenced there?
In response to MuffinMan:
Thanks... I'm still not clear though, at least as to how it relates to my project.
I -am- saving things into an array already. (addr[n] from above)
Here is the class method that is building my addr[n] array for me:
public static function GMapMarker($markerId, $memberObject, $addressObject){
$marker = 'var m_'.$memberObject->Id.'_'.$addressObject->AddressNum.' = new google.maps.LatLng('.$addressObject->Lat.','.$addressObject->Lon.');
marker = new google.maps.Marker({
animation: google.maps.Animation.DROP,
position: m_'.$memberObject->Id.'_'.$addressObject->AddressNum.',
title:"'.addslashes($memberObject->Full_Name).'",
company:"'.addslashes($memberObject->Company).'",
icon:"marker_gd.php?m=' . $markerId . '",
markerid:"'.$markerId.'",
id:"'.addslashes($memberObject->Id).'",
addressnum:"'.addslashes($addressObject->AddressNum).'",
refid:"m_'.$memberObject->Id.'_'.$addressObject->AddressNum.'",
workphone:"'.addslashes($memberObject->Work_Phone).'",
zIndex: '. (100 - preg_replace('/\D/','', $markerId)) .'
});
addr.push(marker);';
return $marker;
}
I have no way of knowing what order/index in the array that particular marker is. However I do have the unique name given and that markers lat/lon coords....
But I am NOT clear how to use it to target a marker later on?
Here's what I used in my implementation:
var markers = [];
for (var index = 0; index < data.length; index++) {
var latlng = new google.maps.LatLng(data[index].lat, data[index].lng);
var marker = new google.maps.Marker({position: latlng, map: map, title: data[index].label, icon: 'images/dot.gif'});
google.maps.event.addListener(marker, 'click', function() {
markers.push(marker); /* marker saved here for later reference*/
});
}
markers[] is populated with the markers you want for later use. E.g. markers[0].
You can add other listeners that javascript supports to handle other events on the marker, such as dragging and hovering.

How to reference a google map marker by it's id and activate it's click event using javascript?

I am dealing with Google Maps here and javascript. I have an existing marker on my Google map and I can click on it and it displays a div. If I click it again, the div disappears. I gave this marker a specific, unique id.
There is also a Polygon on the map. I want when the user clicks on the polygon that the click event is activate for a marker that I will reference by the marker's id.
Is this possible? If so, let's say that the id of the marker is U123. How would I do this?
Here is the code I use to add an event to the polygon click:
google.maps.event.addListener(assetPolygons[polygon_count],'click', function (event) {new google.maps.event.trigger('U123', 'click');});
U123 is the name of the marker id. The above is not working.
var marker = new google.maps.Marker(markerOptions);
marker.setValues({id: 1}); // v3
marker.metadata = {type: "point", id: 1}; //v2 or v3
I guess the better way to do this is to store your marker in a global var and then do
$(".something").click(function(){
new google.maps.event.trigger( marker, 'click' );
// Here marker is a global var so accessible everywhere.
});
Two seconds in google found How to trigger the onclick event of a marker on a Google Maps V3?
The only difference in the function that was stated to work, wich is:
google.maps.event.trigger(markers[i], 'click');
and yours that i can see is the new, try removing it
I built a function that loops through the assetMarkers array that stores each marker. This works:
function ClickMarker(u) {
for (i=0;i<assetMarkers.length;i++) {
if (assetMarkers[i].id == u) {
google.maps.event.trigger(assetMarkers[i], 'click');
i = assetMarkers.length;
}
}
}
In the above function, the variable u is the id of the marker in the array assetMarkers (which is the array storing the map markers). When I create the marker, I set the id using marker.setValues({id: 'U123'}); where U123 is the id of the marker.
I have to loop through the assetMarkers array to find the one I am looking for.
I was hoping, the equivalent of document.getElementById(u) would exist in Google Maps so that I would not have to loop through the array. It would be great, Google API guys, if we programmers could do something like this:
google.maps.event.trigger(google.maps.getElementById(u), 'click');
Thanks for everyone's input! It was very helpful as I am a newbie to Google Maps.

Show only 1 marker at a time fron onClick

I've got the following onClick function...
GEvent.addListener(map, "click", function(overlay, latLng)
{
if (latLng) {
marker = new GMarker(latLng, {draggable:true});
marker.openInfoWindowHtml(mes);
}
// display the lat/lng in your form's lat/lng fields
document.getElementById("lat").value = latLng.lat();
document.getElementById("lng").value = latLng.lng();
});
basically I want to make it so only a marker shows on the most recent click. I've been looking at this question Googlemaps - removing previous marker but can't really figure out how I'd apply that to my code. could someone help me out?
Thanks.
One could use a variable within an object, and determine whether that variable has been set where it tracks the current marker that is visible, and set the marker to be invisible, unset it before adding the marker that is currently being shown.

Categories