Fighting the marker array for the Google Maps API

I started listing my markers separately for my Google Map, but quickly realized that it was ineffective. I tried to create an array to put markers on my map, but it shows nothing, can you see where I made a mistake?

function initialize() { var latlng = new google.maps.LatLng(52.474, -1.868); var myOptions = { zoom: 11, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); var image = 'i/hotel-map-pin.png'; var hotels = [ ['ibis Birmingham Airport', 52.452656, -1.730548, 4], ['ETAP Birmingham Airport', 52.452527, -1.731644, 3], ['ibis Birmingham City Centre', 52.475162, -1.897208, 2] ]; for (var i = 0; i < hotels.length; i++) { var marker = new google.maps.Marker({ position: hotels[1], map: map, icon: image, title: hotels[0], zIndex: hotels[2] }); } } 

Thanks.

+4
source share
2 answers

In your cycle, you get access to the array of hotels at fixed indices (1, 0 and 2), and not to the elements of the array with index i:

  for (var i = 0; i < hotels.length; i++) { var hotel = hotels [i] var marker = new google.maps.Marker({ position: new google.maps.LatLng (hotel[1], hotel[2]), map: map, icon: image, title: hotel[0], zIndex: hotel[3] }); } 

Here is a working example with a fix.

+4
source

Here's the JSFiddle Demo:

First of all, you do not get access to the array of hotels correctly. It should be hotels[i][0] for the header hotels[i][1] and hotels[i][2] for lat and lng and hotels[i][3] for the z-index. Secondly, the position takes a google.maps.LatLng object with lat and lng parameters as a parameter.

 function initialize() { var latlng = new google.maps.LatLng(52.474, -1.868); var myOptions = { zoom: 11, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); var image = 'i/hotel-map-pin.png'; var hotels = [ ['ibis Birmingham Airport', 52.452656, -1.730548, 4], ['ETAP Birmingham Airport', 52.452527, -1.731644, 3], ['ibis Birmingham City Centre', 52.475162, -1.897208, 2] ]; for (var i = 0; i < hotels.length; i++) { var marker = new google.maps.Marker({ position: new google.maps.LatLng(hotels[i][1], hotels[i][2]), map: map, // icon: image, title: hotels[i][0], zIndex: hotels[i][3] }); } } window.onload = initialize; 
+4
source

All Articles