Calculate distance between two points in google maps V3

后端 未结 15 1695
醉梦人生
醉梦人生 2020-11-22 02:27

How do you calculate the distance between two markers in Google maps V3? (Similar to the distanceFrom function inV2.)

Thanks..

相关标签:
15条回答
  • 2020-11-22 03:05

    It's Quite easy using Google Distance Matrix service

    First step is to activate Distance Matrix service from google API console. it returns distances between a set of locations. And apply this simple function

    function initMap() {
            var bounds = new google.maps.LatLngBounds;
            var markersArray = [];
    
            var origin1 = {lat:23.0203, lng: 72.5562};
            //var origin2 = 'Ahmedabad, India';
            var destinationA = {lat:23.0436503, lng: 72.55008939999993};
            //var destinationB = {lat: 23.2156, lng: 72.6369};
    
            var destinationIcon = 'https://chart.googleapis.com/chart?' +
                'chst=d_map_pin_letter&chld=D|FF0000|000000';
            var originIcon = 'https://chart.googleapis.com/chart?' +
                'chst=d_map_pin_letter&chld=O|FFFF00|000000';
            var map = new google.maps.Map(document.getElementById('map'), {
              center: {lat: 55.53, lng: 9.4},
              zoom: 10
            });
            var geocoder = new google.maps.Geocoder;
    
            var service = new google.maps.DistanceMatrixService;
            service.getDistanceMatrix({
              origins: [origin1],
              destinations: [destinationA],
              travelMode: 'DRIVING',
              unitSystem: google.maps.UnitSystem.METRIC,
              avoidHighways: false,
              avoidTolls: false
            }, function(response, status) {
              if (status !== 'OK') {
                alert('Error was: ' + status);
              } else {
                var originList = response.originAddresses;
                var destinationList = response.destinationAddresses;
                var outputDiv = document.getElementById('output');
                outputDiv.innerHTML = '';
                deleteMarkers(markersArray);
    
                var showGeocodedAddressOnMap = function(asDestination) {
                  var icon = asDestination ? destinationIcon : originIcon;
                  return function(results, status) {
                    if (status === 'OK') {
                      map.fitBounds(bounds.extend(results[0].geometry.location));
                      markersArray.push(new google.maps.Marker({
                        map: map,
                        position: results[0].geometry.location,
                        icon: icon
                      }));
                    } else {
                      alert('Geocode was not successful due to: ' + status);
                    }
                  };
                };
    
                for (var i = 0; i < originList.length; i++) {
                  var results = response.rows[i].elements;
                  geocoder.geocode({'address': originList[i]},
                      showGeocodedAddressOnMap(false));
                  for (var j = 0; j < results.length; j++) {
                    geocoder.geocode({'address': destinationList[j]},
                        showGeocodedAddressOnMap(true));
                    //outputDiv.innerHTML += originList[i] + ' to ' + destinationList[j] + ': ' + results[j].distance.text + ' in ' +                    results[j].duration.text + '<br>';
                    outputDiv.innerHTML += results[j].distance.text + '<br>';
                  }
                }
    
              }
            });
          }
    

    Where origin1 is your location and destinationA is destindation location.you can add above two or more data.

    Rad Full Documentation with an example

    0 讨论(0)
  • 2020-11-22 03:05

    To calculate distance on Google Maps, you can use Directions API. That will be one of the easiest way to do it. To get data from Google Server, you can use Retrofit or Volley. Both has their own advantage. Take a look at following code where I have used retrofit to implement it:

    private void build_retrofit_and_get_response(String type) {
    
        String url = "https://maps.googleapis.com/maps/";
    
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    
        RetrofitMaps service = retrofit.create(RetrofitMaps.class);
    
        Call<Example> call = service.getDistanceDuration("metric", origin.latitude + "," + origin.longitude,dest.latitude + "," + dest.longitude, type);
    
        call.enqueue(new Callback<Example>() {
            @Override
            public void onResponse(Response<Example> response, Retrofit retrofit) {
    
                try {
                    //Remove previous line from map
                    if (line != null) {
                        line.remove();
                    }
                    // This loop will go through all the results and add marker on each location.
                    for (int i = 0; i < response.body().getRoutes().size(); i++) {
                        String distance = response.body().getRoutes().get(i).getLegs().get(i).getDistance().getText();
                        String time = response.body().getRoutes().get(i).getLegs().get(i).getDuration().getText();
                        ShowDistanceDuration.setText("Distance:" + distance + ", Duration:" + time);
                        String encodedString = response.body().getRoutes().get(0).getOverviewPolyline().getPoints();
                        List<LatLng> list = decodePoly(encodedString);
                        line = mMap.addPolyline(new PolylineOptions()
                                        .addAll(list)
                                        .width(20)
                                        .color(Color.RED)
                                        .geodesic(true)
                        );
                    }
                } catch (Exception e) {
                    Log.d("onResponse", "There is an error");
                    e.printStackTrace();
                }
            }
    
            @Override
            public void onFailure(Throwable t) {
                Log.d("onFailure", t.toString());
            }
        });
    
    }
    

    Above is the code of function build_retrofit_and_get_response for calculating distance. Below is corresponding Retrofit Interface:

    package com.androidtutorialpoint.googlemapsdistancecalculator;
    
    
    import com.androidtutorialpoint.googlemapsdistancecalculator.POJO.Example;
    
    import retrofit.Call;
    import retrofit.http.GET;
    import retrofit.http.Query;
    
    public interface RetrofitMaps {
    
    
    /*
     * Retrofit get annotation with our URL
     * And our method that will return us details of student.
     */
    @GET("api/directions/json?key=AIzaSyC22GfkHu9FdgT9SwdCWMwKX1a4aohGifM")
    Call<Example> getDistanceDuration(@Query("units") String units, @Query("origin") String origin, @Query("destination") String destination, @Query("mode") String mode);
    

    }

    I hope this explains your query. All the best :)

    Source: Google Maps Distance Calculator

    0 讨论(0)
  • 2020-11-22 03:07

    Had to do it... The action script way

    //just make sure you pass a number to the function because it would accept you mother in law...
    public var rad = function(x:*) {return x*Math.PI/180;}
    
    protected  function distHaversine(p1:Object, p2:Object):Number {
        var R:int = 6371; // earth's mean radius in km
        var dLat:Number = rad(p2.lat() - p1.lat());
        var dLong:Number = rad(p2.lng() - p1.lng());
    
        var a:Number = Math.sin(dLat/2) * Math.sin(dLat/2) +
                    Math.cos(rad(p1.lat())) * Math.cos(rad(p2.lat())) * Math.sin(dLong/2) * Math.sin(dLong/2);
        var c:Number = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
        var d:Number = R * c;
    
        return d;
    }
    
    0 讨论(0)
提交回复
热议问题