1

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?

4

1 回答 1

4

初始化的 map 变量是初始化函数的本地变量。

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

将该行更改为(删除它前面的“var”):

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

或(另一种选择),将其传递给 createMarker 调用(并删除全局范围内的定义):

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

并这样称呼它:

createMarker(map, LatLngB2,"B2");// removed the unused fourth argument...
于 2013-05-24T16:20:14.067 回答