本文介绍了获取从地图中心到地图开始/结束位置的距离(以kms为单位)-Google Maps Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用 Google Maps Javascript 获取从mapCenter()到地图开始/结束位置的距离(以kms为单位)?有办法吗?
How can I get distance(in kms) from mapCenter() to start/end position of map using Google Maps Javascript? Is there a way to do this?
推荐答案
您可能正在寻找 getBounds
函数:
You probably looking for a getBounds
function:
然后,您可以利用几何库特别是 google.maps.geometry.spherical.computeDistanceBetween
函数用于计算两个点之间的距离(默认情况下以米为单位).
Then you could utilize Geometry Library in particular google.maps.geometry.spherical.computeDistanceBetween
function to calculate distance between two points (in meters by default).
示例
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'/>
这篇关于获取从地图中心到地图开始/结束位置的距离(以kms为单位)-Google Maps Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!