简体   繁体   中英

Google Maps API 3 - Javascript: Markers don't appear if created in function

Here's the problem: if i try to create markers in the initialize() function everything works, but if i try to do it in another function, markers won't appear.

GoogleMap.js

var map;
function initialize() {             
var initial_mapcenter = new google.maps.LatLng(45.697068,9.668598);
var map = new google.maps.Map(document.getElementById("map-canvas"),{ zoom: 10, center: initial_mapcenter, mapTypeId: google.maps.MapTypeId.ROADMAP});

var LatLngA1 = new google.maps.LatLng(45.69467,9.603195);
var marker = new google.maps.Marker({
            position: LatLngA1,
            map: map,
            title: "A1"
        });

var LatLngB2 = new google.maps.LatLng(45.653408,9.618301);
createMarker(LatLngB2,"B2","Test B2");
}

function createMarker(point,name) {
    var marker = new google.maps.Marker({
        position: point,
        map: map,
        title: name
    });
}

The first one (A1) appears, the second one (B2) doesn't.

I would like to mantain the function createMarker, because i want to use it to add InfoWindows too.

Should i create new markers in the initialize function (and then modify them) or is there some kind of error in my code?

The initialized map variable is local to your initialize function.

var map = new google.maps.Map(document.getElementById("map-canvas"),{ zoom: 10, center: initial_mapcenter, mapTypeId: google.maps.MapTypeId.ROADMAP});

Change that line to (remove the "var" in front of it):

map = new google.maps.Map(document.getElementById("map-canvas"),{ zoom: 10, center: initial_mapcenter, mapTypeId: google.maps.MapTypeId.ROADMAP});

or (another option), pass it into the createMarker call (and remove the definition in the global scope):

function createMarker(map, point,name) {
  var marker = new google.maps.Marker({
    position: point,
    map: map,
    title: name
  });
}

and call it like this:

createMarker(map, LatLngB2,"B2");// removed the unused fourth argument...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM