Javascript Google Maps Api, multiple markers with links, only geoceder -
i've got problems put links on multiple markers, can show markers on map, when try tu put link on them, have same link on markers, last. here provide sample code:
<div id="map" style="height: 400px; width:100%;"></div> <script> var markers = [{"name":"vasto","url":"http://www.google.com"},{"name":"chieti","url":"http://www.wikipedia.com"}]; var geocoder; var map; var latlng; var url; console.log(markers); function initmap() { latlng = {lat: 42.2872297, lng: 13.3403448}; map = new google.maps.map(document.getelementbyid('map'), {zoom: 8, center: latlng}); geocoder = new google.maps.geocoder(); setmarkers(); } function setmarkers() { var marker, i, url; for( = 0; < markers.length; i++ ) { url = markers[i].url; geocoder.geocode({'address': markers[i].name}, function(results, status) { if (status === 'ok') { marker = new google.maps.marker({ map: map, position: results[0].geometry.location, title: results[0].address_components[0].long_name, }); google.maps.event.addlistener(marker, "click", function() { window.location.href = url; }); } else { /*console.log('geocode not successful following reason: ' + status);*/ }}); } } </script> <script src="https://maps.googleapis.com/maps/api/js?key=mykey&callback=initmap" async defer></script>
any solutions? in advance
due asynchronous code, need change code bit
function setmarkers() { markers.foreach(function(item) { var url = item.url; geocoder.geocode({'address': item.name}, function(results, status) { if (status === 'ok') { var marker = new google.maps.marker({ map: map, position: results[0].geometry.location, title: results[0].address_components[0].long_name, }); google.maps.event.addlistener(marker, "click", function() { window.location.href = url; }); } else { /*console.log('geocode not successful following reason: ' + status);*/ }}); } }
Comments
Post a Comment