简体   繁体   English

Google Maps API 3 - Javascript:如果在功能中创建标记,则不会出现标记

[英]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. 这是问题所在:如果我尝试在initialize()函数中创建标记,一切正常,但如果我尝试在另一个函数中执行,则不会出现标记。

GoogleMap.js 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. 第一个(A1)出现,第二个(B2)没有。

I would like to mantain the function createMarker, because i want to use it to add InfoWindows too. 我想保留createMarker函数,因为我想用它来添加InfoWindows。

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): 将该行更改为(删除前面的“var”):

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): 或(另一个选项),将其传递给createMarker调用(并删除全局范围中的定义):

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...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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