2017-04-10 25 views
0

有沒有什麼方法可以將經過的URL的經度和緯度放入標記中。所以基本上用戶會複製並粘貼Google地圖上的「分享」網址。如何使谷歌地圖檢測到通過的Google地圖URL的位置

E.G.地方:https://www.google.co.nz/maps/place/The+White+House/@38.8976763,-77.0387238,17z/data=!3m1!4b1!4m5!3m4!1s0x89b7b7bcdecbb1df:0x715969d86d0b76bf!8m2!3d38.8976763!4d-77.0365298?hl=en

或直接定位: https://www.google.co.nz/maps/place/38%C2%B054'53.8%22N+77%C2%B006'01.6%22W/@38.914936,-77.102638,17z/data=!3m1!4b1!4m5!3m4!1s0x0:0x0!8m2!3d38.914936!4d-77.100444?hl=en

我想初始化代碼創建在該共享URL位置的標記。

到目前爲止,從其他問題我已經看到了GeoCode API的使用,但我不確定上面的示例URL可以如何解析和在JS中提取數據。值得讚賞的是,任何Ajax調用API的例子或類似的東西都會被讚賞。

回答

0

該URL包含經緯度,因此您可以輕鬆提取它們。調用putMarkerAtURLCoordinates(SHARED_URL)會在URL的座標處放置一個標記,前提是您的Google地圖實例稱爲「地圖」。

function putMarkerAtURLCoordinates(url){ 
    //get the latlng object from url 
    var myLatLng = getLatLngFromURL(url) 
    //create the marker and assign it to the map 
    var marker = new google.maps.Marker({ 
      position: myLatLng, 
      map: map, 
      title: 'Marker title here' 
    }); 
} 

function getLatLngFromURL(url){ 
    //decode url incase its urlencoded 
    url = decodeURIComponent(url) 
    //find index of @ character 
    var atindex = url.indexOf("@") 
    //cut off the part before the @ and split the rest up by the comma separator 
    var urlparts = url.slice(atindex+1).split(",") 
    //parse the values as floats 
    var lat = parseFloat(urlparts[0]) 
    var lng = parseFloat(urlparts[1]) 
    //return as object 
    return {lat:lat,lng:lng} 
} 

這不是一個穩定的解決方案,但...如果谷歌改變了他們的URL方案,這將不再工作。