如何從mapCenter()獲取地圖的開始/結束位置的距離(單位爲千米)使用谷歌地圖Javascript?有沒有辦法做到這一點?從地圖中心到地圖的開始/結束位置的距離(單位爲公里) - Google Maps Javascript
回答
你可能尋找一個getBounds
function:
返回當前視口的緯度/經度範圍。如果世界上有多個 副本可見,則邊界的範圍爲-180 至180度(含)。如果地圖尚未初始化(即 mapType仍爲空),或未設置中心和縮放,則 結果爲空或未定義。
然後,您可以利用Geometry Library特別是google.maps.geometry.spherical.computeDistanceBetween
函數來計算兩點之間的距離(默認以米爲單位)。
例
function initialize() {
var center = new google.maps.LatLng(55.755327, 37.622166);
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 12,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
google.maps.event.addListener(map, 'bounds_changed', function() {
var bounds = map.getBounds();
var start = bounds.getNorthEast();
var end = bounds.getSouthWest();
var distStart = google.maps.geometry.spherical.computeDistanceBetween (center, start)/1000.0;
var distEnd = google.maps.geometry.spherical.computeDistanceBetween (center, end)/1000.0;
document.getElementById('output').innerHTML += 'Distiance from center to start:' + distStart;
document.getElementById('output').innerHTML += 'Distiance from center to end:' + distEnd + '<br/>';
});
}
google.maps.event.addDomListener(window, 'load', initialize);
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=geometry"></script>
<div id="map" style="width: 500px; height: 350px;"></div>
<div id='output'/>
我檢查了你的代碼,它的工作正常。但是我使用了''。如果我使用幾何替換庫,則位置API不起作用。如何解決這個問題? –
您只需加載'places'和'geometry'庫:https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=geometry,places 欲瞭解更多詳情,請參見[Google Maps Javascript API](https://developers.google.com/maps/documentation/javascript/libraries)文檔 –
我使用** libraries = geometry,places **加載了這兩個文件。現在都很好。非常感謝您的時間 –
- 1. 在Google地圖上添加開始和結束位置
- 2. Google Maps最後的好地圖位置
- 3. 將Google地圖標記拖到地圖的中心位置嗎?
- 4. Google Maps API - 根據行駛距離更新地圖上的當前位置
- 5. PhoneGap地理位置:href到Google地圖
- 6. JavaScript Google Maps API - 用戶位置上的中心未加載地圖
- 7. 兩個位置之間的距離 - Google地圖
- 8. 在Google地圖上搜索具體位置可配置距離
- 9. 地理位置+ Google Maps API?
- 10. 設置Google地圖API的位置
- 11. Google Maps JavaScript API地理位置標記
- 12. Google地方找不到Google地圖API的位置
- 13. 地理位置距離
- 14. 從初始位置,方位和距離得到的位置
- 15. 谷歌地圖「我的位置」javascript API
- 16. 如何設置Google地圖的中心位置
- 17. Google地圖標記距離?
- 18. 使用地理位置設置谷歌地圖中心
- 19. 地理位置+距離測量
- 20. android google地圖位置
- 21. Google地圖位置服務
- 22. 在Maps Api for Android中設置默認的我的位置Google地圖圖標
- 23. 谷歌地圖與一些距離放置位置
- 24. 使用地理位置確定距離固定點的距離
- 25. 使用Google Maps Javascript結合地理位置和標記
- 26. Google Maps Api,通過地圖上的路線獲取位置
- 27. Google Maps API,setDirections()不得更新地圖的位置
- 28. 通過使用yii2-google-maps-markers設置Google地圖中心
- 29. 在Google地圖中設置InfoWindow位置
- 30. Google Maps Api v3 - 在運行時設置地圖位置
直線距離 - 見http://stackoverflow.com/questions/1502590/calculate-distance-between-two-points-in-google- maps-v3 –
我只有mapCenter()lat,lng(** say ** p1)。我怎樣才能在地圖上獲得左開始/右端經緯度,lng(**說** p2)? –
這將是https://developers.google.com/maps/documentation/javascript/reference?hl=en - 'getBounds()'(剛好在'getCenter()'之上 - 我猜你知道) –