获取从地图中心到地图开始/结束位置的距离(以kms为单位)-Google Maps Javascript [英] Getting distance(in kms) from map center to start/end position of map - Google Maps Javascript

查看:50
本文介绍了获取从地图中心到地图开始/结束位置的距离(以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:

返回当前视口的纬度/经度边界.如果不止一个世界的副本可见,经度范围为-180至180度(含).如果地图尚未初始化(即mapType仍然为null),或者尚未设置居中和缩放,则结果为null或未定义.

Returns the lat/lng bounds of the current viewport. If more than one copy of the world is visible, the bounds range in longitude from -180 to 180 degrees inclusive. If the map is not yet initialized (i.e. the mapType is still null), or center and zoom have not been set then the result is null or undefined.

然后,您可以利用几何库特别是 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆