2011-05-31 71 views
10

我想在地图上点击一个区域。该脚本不起作用并且页面重新加载。也许有人可以看到这个问题。谷歌地图PanTo OnClick

我的功能

function clickroute(lati,long) { 

     map = google.maps.Map(document.getElementById("map_canvas")); 
     map.panTo(lati,long) 
    } 

而其余的

var directionDisplay; 
    var directionsService = new google.maps.DirectionsService(); 
    var map; 

    function initialize() { 
     geocoder = new google.maps.Geocoder(); 
    directionsDisplay = new google.maps.DirectionsRenderer(); 
    var chicago = new google.maps.LatLng(41.850033, -87.6500523); 
    var myOptions = { 
     zoom:10, 
     mapTypeId: google.maps.MapTypeId.ROADMAP, 
     center: chicago 
    } 
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 

    var address = 'virginia water'; 
    geocoder.geocode({ 'address': address}, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
     map.setCenter(results[0].geometry.location); 
     var marker = new google.maps.Marker({ 
      map: map, 
      position: results[0].geometry.location 
     }); 
     } 
    }); 
    directionsDisplay.setMap(map); 
    } 

    function calcRoute() { 
    var start = document.getElementById("start").value; 
    var end = document.getElementById("end").value; 
    var request = { 
     origin:start, 
     destination:end, 
     travelMode: google.maps.DirectionsTravelMode.DRIVING 
    }; 
    directionsService.route(request, function(response, status) { 
     if (status == google.maps.DirectionsStatus.OK) { 
     directionsDisplay.setDirections(response); 
     } 
    }); 
    } 

我的事件

<a href="" onclick="clickroute(51.433373, -0.712251)">test</a> 

回答

25

的问题是您使用map.panTo(latitude,longitude)但谷歌地图API使用这个:panTo(latLng myLatLng)哪里latLng是谷歌地图类。

尝试这样的事情(未经测试)

function clickroute(lati,long) { 
     var latLng = new google.maps.LatLng(lati, long); //Makes a latlng 
     map.panTo(latLng); //Make map global 
    } 

here获取更多信息。

编辑 正如其他人所说,你不想重拍一张新地图。也许它更容易使其成为全球?

+0

就像一个魅力!有没有为此定制?像流体运动一样?现在它捕捉到的位置和地图渲染后,慢慢地... – nclsvh 2015-12-13 19:32:32

0

线...

map = google.maps.Map(document.getElementById("map_canvas")); 

..其实是试图创建的#map_canvas事业部内的新地图。由于该映射应该已经存在,因此您不需要该赋值语句。只是打电话

map.panTo(lati,long) 

应该工作吗?

编辑:对不起,SSRide360是正确的,应该是...

map.panTo(new google.maps.LatLng(lati, long)); 
3

的哑剧接受经纬度对象作为参数,而不仅仅是坐标。在将它传递给panTo方法之前创建一个LatLng对象。

function clickroute(lati,long) { 
    map.panTo(new google.maps.LatLng(lati,long)); 
    return false; //this will cancel your navigation 
} 

您的页面重新加载,因为您没有取消onClick中的导航事件,您将其放入锚标记中。请参阅上面代码中的评论。

和其他人一样,从这个函数中取出地图变量,并使地图全局。

2

您还可以设置一个新的标记在飞行:

var LatLng = new google.maps.LatLng(lat, lng); 
    var marker = new google.maps.Marker({ 
       content: "<h2>Hier wohne ich!</h2>", 
       map: map,position: results[0].geometry.location 
       }); 
    map.panTo(LatLng);