0

如何向地图添加新标记?我设法显示了地图function startGoogleMaps() ,但我的功能 ( onclick()) 不起作用。

function startGoogleMaps(){    
    var map = new google.maps.Map(document.getElementById('canvasMap'), {
        zoom: 5,
        center: initCenter,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });            
}

document.getElementById("testButton").onclick = function(){
    var marker = new google.maps.Marker({
      position: (37, -97),
      map: map,
      title:"Hello World!"});
}
4

2 回答 2

2

尝试map在绑定 click 事件的同一范围内定义对象:

var map = null;

function startGoogleMaps(){    
    map = new google.maps.Map(document.getElementById('canvasMap'), {
        zoom: 5,
        center: initCenter,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });            
}

document.getElementById("testButton").onclick = function(){
    var marker = new google.maps.Marker({
      position: (37, -97),
      map: map,
      title:"Hello World!"});
}

另请注意,您需要将您的职位作为以下实例传递google.maps.LatLng

      ...
      position: google.maps.LatLng(37, -97),
      ...
于 2012-10-22T21:58:38.423 回答
1

请记住,Javascript 使用函数范围。您需要map像这样全局声明:

var map;

function startGoogleMaps(){    
    map = new google.maps.Map(document.getElementById('canvasMap'), {
        zoom: 5,
        center: initCenter,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });            
}

document.getElementById("testButton").onclick = function(){
    var marker = new google.maps.Marker({
      position: new google.maps.LatLng(37, -97),
      map: map,
      title:"Hello World!"});
}

此外,标记本身可能超出了您的地图范围,因此您可以使用map.fitBounds它来正确显示它:

document.getElementById("testButton").onclick = function(){
    var marker = new google.maps.Marker({
      position: new google.maps.LatLng(37, -97),
      map: map,
      title:"Hello World!"});

    var latlngbounds = new google.maps.LatLngBounds();
    latlngbounds.extend(new google.maps.LatLng(37, -97));
    map.fitBounds(latlngbounds);
}
于 2012-10-22T21:58:39.653 回答