2011-05-31 70 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);