Creating a custom google map with multiple markers and pop-ups - Problems

Trying to create a custom google map, I wrote the code, but something was wrong, I thought if anyone could indicate what I did wrong. The code is here:

<script type="text/javascript"> function initialize() { var myLatlng = new google.maps.LatLng(30,0); var myOptions = { zoom: 2, center: myLatlng, mapTypeId: google.maps.MapTypeId.TERRAIN } var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); var countries = Array(); countries.push({ marker: new google.maps.Marker({position: new google.maps.LatLng(4.52,115), map: map, title: 'Test'}), infowindow: new google.maps.InfoWindow({content: "Hello world"}) }); countries.push({ marker: new google.maps.Marker({position: new google.maps.LatLng(42.45,23.20), map: map, title: 'Test2'}), infowindow: new google.maps.InfoWindow({content: "Hello world2"}) }); countries.push({ marker: new google.maps.Marker({position: new google.maps.LatLng(12.15,-1.30), map: map, title: 'Test3'}), infowindow: new google.maps.InfoWindow({content: "Hello world3"}) }); for each (var item in countries) { google.maps.event.addListener(item.marker, 'click', function() { item.infowindow.open(map, item.marker); }); } 

0
source share
2 answers

Besides using the wrong for loop style , you are trying to make a function in a loop . This is a very common mistake. . Since JS has a level scope rather than a block level, this does not work as you might expect.

Try the following:

 function makeCallback(country) { return function () { country.infowindow.open(map, country.marker); }; } var item; for (var i=0; i<countries.length; i++) { item = countries[i]; google.maps.event.addListener(item.marker, 'click', makeCallback(item)); } 
0
source

Everything seems to be fine, I see a map with 3 markers, but I don’t know what is hard to say.

A few hunches:

  • You miss the curly brace at the end that closes the initialization
  • Do you have a div with id "map_canvas"?
  • Is initialization called from anywhere?
  • Have you enabled javascript google maps?
0
source

Source: https://habr.com/ru/post/1433332/


All Articles