2012-10-22 116 views
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!"}); 
} 
+0

在哪里标记应该出现吗?即什么是位置(37,-97)'? – jsalonen

+0

纬度/经度 – Andrew

+0

问题出在'位置:(37,-97)'需要它成为'new google.maps.LatLng(37,-97)' – Andrew

回答

2

尝试定义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

请记住,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); 
} 
+0

当我使用'map.fitBounds(latlngbounds);'我的地图消失 – Andrew