javascript - Google Maps JS API v3 - Simple Multiple Marker Example -


fairly new google maps api. i've got array of data want cycle through , plot on map. seems simple, multi-marker tutorials have found quite complex.

let's use data array google's site example:

var locations = [   ['bondi beach', -33.890542, 151.274856, 4],   ['coogee beach', -33.923036, 151.259052, 5],   ['cronulla beach', -34.028249, 151.157507, 3],   ['manly beach', -33.80010128657071, 151.28747820854187, 2],   ['maroubra beach', -33.950198, 151.259302, 1] ]; 

i want plot of these points , have infowindow pop when clicked display name.

this simplest reduce to:

<!doctype html> <html>  <head>    <meta http-equiv="content-type" content="text/html; charset=utf-8" />    <title>google maps multiple markers</title>    <script src="http://maps.google.com/maps/api/js?sensor=false"            type="text/javascript"></script> </head>  <body>   <div id="map" style="width: 500px; height: 400px;"></div>    <script type="text/javascript">     var locations = [       ['bondi beach', -33.890542, 151.274856, 4],       ['coogee beach', -33.923036, 151.259052, 5],       ['cronulla beach', -34.028249, 151.157507, 3],       ['manly beach', -33.80010128657071, 151.28747820854187, 2],       ['maroubra beach', -33.950198, 151.259302, 1]     ];      var map = new google.maps.map(document.getelementbyid('map'), {       zoom: 10,       center: new google.maps.latlng(-33.92, 151.25),       maptypeid: google.maps.maptypeid.roadmap     });      var infowindow = new google.maps.infowindow();      var marker, i;      (i = 0; < locations.length; i++) {         marker = new google.maps.marker({         position: new google.maps.latlng(locations[i][1], locations[i][2]),         map: map       });        google.maps.event.addlistener(marker, 'click', (function(marker, i) {         return function() {           infowindow.setcontent(locations[i][0]);           infowindow.open(map, marker);         }       })(marker, i));     }   </script> </body> </html> 

screenshot:

google maps multiple markers

there closure magic happening when passing callback argument addlistener method. can quite tricky topic, if not familiar how closures work. suggest checking out following mozilla article brief introduction, if case:


Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -