【问题标题】:Calculate distance between users location and all the markers on map计算用户位置与地图上所有标记之间的距离
【发布时间】:2016-08-28 06:27:12
【问题描述】:

我自己做了一些 Google Mpas 的东西,但停止了距离计算。 我有一个定位用户当前位置标记的功能:

function myLocationMarker(latLng) {
    var markerOptions = {
        position: latLng,
        map: map,
        clickable: true
    }
    var myMarker = new MarkerWithLabel(markerOptions);

这个函数会放置其他标记。我从数据库中获取数据,它放置了大约 1000 个标记。

var markers = []; //blank array from markers
function addMarker(lat, lng, info) { //info - needed for database
    var pt = new google.maps.LatLng(lat, lng);
    var marker = new google.maps.Marker({ //marker options
        position: pt,
        icon: icon,
        map: map
    });
    markers.push(marker); //pushing every marker to markers array

但我需要的是它们之间的距离。 如何从addMarker 函数计算myLocationMarker 与地图上所有其他标记之间的距离?

【问题讨论】:

    标签: javascript google-maps google-maps-api-3


    【解决方案1】:

    您可以使用directionsService,注意地图上两个标记之间的距离取决于您选择的travelling mode"DRIVING""WALKING""BICYCLING""TRANSIT")。

    如果您想计算空中距离,您将需要一些带有 Haversine 公式的几何体(在此处查看代码:https://stackoverflow.com/a/1502821/2314737

    这是"DRIVING" 的示例

    function calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointB, outputTxt) {
      var selectedMode = "DRIVING";
      directionsService.route({
        origin: pointA,
        destination: pointB,
        unitSystem: google.maps.UnitSystem.METRIC,
        travelMode: google.maps.TravelMode[selectedMode]
      }, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
          directionsDisplay.setDirections(response);
    
          outputTxt.innerHTML = Math.round(directionsDisplay.getDirections().routes[directionsDisplay.getRouteIndex()].legs[0].distance.value / 1000) + "Km";
        } else {
          window.alert('Directions request failed due to ' + status);
        }
      });
    }
    

    这是一个演示 http://jsfiddle.net/user2314737/fLogwsff/

    编辑:或者,您可以使用 spherical geometry 包中的 computeDistanceBetween 函数

    computeDistanceBetween(从:LatLng,到:LatLng,半径?:数字)
    返回值:number 返回两个 LatLng 之间的距离(以米为单位)。 您可以选择指定自定义半径。半径默认为 地球半径。

    var distance = google.maps.geometry.spherical.computeDistanceBetween(pointA, pointB);
    // by default distance is in meters
    distance = Math.round(distance/ 1000) + "Km";
    

    更新的演示:http://jsfiddle.net/user2314737/qxrg4o3y/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-01
      • 1970-01-01
      • 2020-06-02
      • 1970-01-01
      • 1970-01-01
      • 2011-12-24
      相关资源
      最近更新 更多