添加标记到谷歌地球

时间:2012-10-22 21:48:07

标签: javascript google-maps

如何在地图中添加新标记?我设法显示地图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!"});
}

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分: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);
}