Distance between points google maps android

Найти расстояние между двумя точками на карте с помощью Google Map API V2

Я использую Google map api v2 в своем приложении для android, я могу показать карту и поместить на нее маркеры, но теперь я застрял с проблемой, в которой мне нужно узнать расстояние между двумя маркерами или точками, размещенными на карте, я уже прошел через документы, но не нашел ничего полезного в этом случае.

Если кто-нибудь знает, как решить эту проблему, пожалуйста, помогите мне.

15 ответов:

вы можете использовать следующий метод, который даст вам точный результат

на Google Map API V2 у вас есть LatLng объект, так что вы не можете использовать distanceTo (пока).

затем вы можете использовать следующий код, учитывая oldPosition и newPosition are LatLng объекты :

дополнительные информация о Location классе этой ссылке

вы должны использовать расположение android

Вы можете сделать:

и вы получите расстояние в метрах между location1 и location2 в метрах. И свекла между латлонга и латлонгб.

приходя довольно поздно, но видя, что это один из лучших результатов в поиске Google по теме, я поделюсь другим способом:

используйте один лайнер с Googles служебный класс SphericalUtil

вам понадобятся служебные классы:

Вы можете просто включить их в свой проект с помощью Gradle в:

@Салман Хан То, что предложил Усман курд, идеально. Единственное, что я нашел, что можно исправить, это то, что «для google maps v2 мы используем LatLng класса. Так что ниже приведен код Усман курд, который может быть использован для Google Maps v2. Я проверил, что он работает идеально.

все эти ответы дадут вам расстояние в прямой линии. Если вам нужно получить расстояние по дороге, вы должны проанализировать JSON, который Google отправляет вам обратно после вызова его службы. Вы можете использовать этот метод:

lat1 и lon1-координаты начала координат, lat2 и lon2-координаты места назначения.

простая функция util для вычисления расстояния между двумя геоточек:

расстояние между двумя географическими координатами можно найти с помощью формула Гаверсинуса . Эта формула эффективна для вычисления расстояния в сферическом теле, т. е. земле в нашем случае.

чтобы получить расстояние между двумя точками попробовать этот код..

вы можете использовать эту функцию. Я использовал его в своем проекте.

Это старый вопрос со старыми ответами. Я хочу выделить обновленный способ расчета расстояния между двумя точками. К настоящему времени мы должны быть знакомы с классом утилиты «SphericalUtil». Вы можете получить расстояние, используя это.

ЭТО ПРОСТОЙ И ИДЕАЛЬНЫЙ КОД ДЛЯ ОПРЕДЕЛЕНИЯ ПРОДОЛЖИТЕЛЬНОСТИ И РАССТОЯНИЯ

Шаг 1; (добавьте это и синхронизируйте в своем gradle)

Шаг 2: (запишите это в свой метод триггера)

Шаг 3: (копировать и вставить в свой класс)

в приложении Android google maps есть очень простой способ найти расстояние между двумя местоположениями, для этого выполните следующие простые шаги:

при первом открытии приложения перейдите в раздел «ваша временная шкала» из капли меню в левом верхнем углу.

Как только откроется новый windwo, выберите из настроек в верхнем правом меню и выберите «Добавить место».

  • добавьте свои места и назовите их lilke point 1, point 2 или любое легко запоминающееся имя.
  • как только ваши места будут добавлены и помечены, вернитесь в Главное окно вашего приложения google.
  • нажать на синий круг со стрелкой в правом нижнем углу.
  • откроется новый windwo, и вы можете увидеть, что в верхней части есть два текстовых поля, в которых вы можете добавить свои «из местоположения» и «местоположение расстояния».
  • нажмите на любое текстовое поле и введите сохраненное местоположение в пункте 3.
  • нажмите на другое текстовое поле и добавить следующее сохраненное местоположение.
  • таким образом, google maps рассчитает расстояние между двумя местоположениями и покажет вам синий путь на карте ..
  • Источник

    Overview

    This service is also available as part of the client-side Maps JavaScript API, or for server-side use with the Java Client, Python Client, Go Client and Node.js Client for Google Maps Services.

    Introduction

    The Distance Matrix API is a service that provides travel distance and time for a matrix of origins and destinations. The API returns information based on the recommended route between start and end points, as calculated by the Google Maps API, and consists of rows containing duration and distance values for each pair.

    Note: This service does not return detailed route information. Route information can be obtained by passing the desired single origin and destination to the Directions API.

    Before you begin

    This document is intended for developers who wish to compute travel distance and time between a number of points within maps provided by one of the Google Maps APIs. It provides an introduction to using the API and reference material on the available parameters.

    Before you start developing with the Distance Matrix API, review the authentication requirements (you need an API key) and the API usage and billing information (you need to enable billing on your project).

    Distance Matrix requests

    A Distance Matrix API request takes the following form:

    where outputFormat may be either of the following values:

    • json (recommended), indicates output in JavaScript Object Notation (JSON); or
    • xml , indicates output as XML.

    Note: URLs must be properly encoded to be valid and are limited to 8192 characters for all web services. Be aware of this limit when constructing your URLs. Note that different browsers, proxies, and servers may have different URL character limits as well.

    Читайте также:  Как заблокировать номер андроиде

    Request parameters

    Certain parameters are required while others are optional. As is standard in URLs, all parameters are separated using the ampersand ( & ) character. All reserved characters (for example the plus sign «+») must be URL-encoded. The list of parameters and their possible values are enumerated below.

    Required parameters

    destinations

    One or more locations to use as the finishing point for calculating travel distance and time. The options for the destinations parameter are the same as for the origins parameter.

    origins

    The starting point for calculating travel distance and time. You can supply one or more locations separated by the pipe character (|), in the form of a place ID, an address, or latitude/longitude coordinates:

    • Place ID: If you supply a place ID, you must prefix it with place_id: .
    • Address: If you pass an address, the service geocodes the string and converts it to a latitude/longitude coordinate to calculate distance. This coordinate may be different from that returned by the Geocoding API, for example a building entrance rather than its center.

    Optional parameters

    arrival_time

    Specifies the desired time of arrival for transit directions, in seconds since midnight, January 1, 1970 UTC. You can specify either departure_time or arrival_time , but not both. Note that arrival_time must be specified as an integer.

    avoid

    Distances may be calculated that adhere to certain restrictions. Restrictions are indicated by use of the avoid parameter, and an argument to that parameter indicating the restriction to avoid. The following restrictions are supported:

    • tolls indicates that the calculated route should avoid toll roads/bridges.
    • highways indicates that the calculated route should avoid highways.
    • ferries indicates that the calculated route should avoid ferries.
    • indoor indicates that the calculated route should avoid indoor steps for walking and transit directions.

    departure_time

    Specifies the desired time of departure. You can specify the time as an integer in seconds since midnight, January 1, 1970 UTC. If a departure_time later than 9999-12-31T23:59:59.999999999Z is specified, the API will fall back the departure_time to 9999-12-31T23:59:59.999999999Z. Alternatively, you can specify a value of now, which sets the departure time to the current time (correct to the nearest second). The departure time may be specified in two cases:

    • For requests where the travel mode is transit: You can optionally specify one of departure_time or arrival_time . If neither time is specified, the departure_time defaults to now (that is, the departure time defaults to the current time).
    • For requests where the travel mode is driving: You can specify the departure_time to receive a route and trip duration (response field: duration_in_traffic) that take traffic conditions into account. The departure_time must be set to the current time or some time in the future. It cannot be in the past.

    language

    The language in which to return results.

    For the calculation of distances and directions, you may specify the transportation mode to use. By default, DRIVING mode is used. By default, directions are calculated as driving directions. The following travel modes are supported:

    • driving (default) indicates standard driving directions or distance using the road network.
    • walking requests walking directions or distance via pedestrian paths & sidewalks (where available).
    • bicycling requests bicycling directions or distance via bicycle paths & preferred streets (where available).
    • transit requests directions or distance via public transit routes (where available). If you set the mode to transit, you can optionally specify either a departure_time or an arrival_time . If neither time is specified, the departure_time defaults to now (that is, the departure time defaults to the current time). You can also optionally include a transit_mode and/or a transit_routing_preference .

    region

    traffic_model

    Specifies the assumptions to use when calculating time in traffic. This setting affects the value returned in the duration_in_traffic field in the response, which contains the predicted time in traffic based on historical averages. The traffic_model parameter may only be specified for driving directions where the request includes a departure_time . The available values for this parameter are:

    • best_guess (default) indicates that the returned duration_in_traffic should be the best estimate of travel time given what is known about both historical traffic conditions and live traffic. Live traffic becomes more important the closer the departure_time is to now.
    • pessimistic indicates that the returned duration_in_traffic should be longer than the actual travel time on most days, though occasional days with particularly bad traffic conditions may exceed this value.
    • optimistic indicates that the returned duration_in_traffic should be shorter than the actual travel time on most days, though occasional days with particularly good traffic conditions may be faster than this value.

    The default value of best_guess will give the most useful predictions for the vast majority of use cases. It is possible the best_guess travel time prediction may be shorter than optimistic , or alternatively, longer than pessimistic , due to the way the best_guess prediction model integrates live traffic information.

    transit_mode

    Specifies one or more preferred modes of transit. This parameter may only be specified for transit directions. The parameter supports the following arguments:

    • bus indicates that the calculated route should prefer travel by bus.
    • subway indicates that the calculated route should prefer travel by subway.
    • train indicates that the calculated route should prefer travel by train.
    • tram indicates that the calculated route should prefer travel by tram and light rail.
    • rail indicates that the calculated route should prefer travel by train, tram, light rail, and subway. This is equivalent to transit_mode=train|tram|subway .

    transit_routing_preference

    Specifies preferences for transit routes. Using this parameter, you can bias the options returned, rather than accepting the default best route chosen by the API. This parameter may only be specified for transit directions. The parameter supports the following arguments:

    • less_walking indicates that the calculated route should prefer limited amounts of walking.
    • fewer_transfers indicates that the calculated route should prefer a limited number of transfers.

    units

    Specifies the unit system to use when displaying results.

    Distance Matrix examples

    The following example uses latitude/longitude coordinates to specify the destination coordinates:

    Источник

    Google Maps Distance Calculator using Google Maps API

    Hello guys, welcome to a new Android Tutorial. In this tutorial we will be creating a Google Maps Distance Calculator Android Application.

    I have already posted a Google Maps Tutorial. I would suggest you to go through the previous Google Maps Tutorial before following this Google Maps Distance Calculator Tutorial.

    So in this app we will calculate the distance between two coordinates of the map. We will also draw a path between the given coordinates. So lets start.

    Google Maps Distance Calculator Demo

    You can check out this video demo before moving ahead to the tutorial.


    Now if you want to create the same then move ahead to this Google Maps Distance Calculator Tutorial.

    Creating the Android Project

    • So open Android Studio and create a new project. Now you have to select Maps Activity. I will not be discussing in details. You can check the previous google maps tutorial.
    • You also need your API Key, which you can get from google developer console. I have explained these stuffs on previous post. But one more thing here we need to do. We have the API key for Android. But for Google Maps Distance Calculator App we also need an API Key for Server.
    • Go to Google Maps Direction API. And click on GET A KEY.

    • Now select your project and click on continue.

    • Now go to New Credential and create a Server Key (I am assuming you already have the Android Key).

    • Note down your server key and come back to your project in Android Studio.

    Adding Google Maps Android API utility and Volley Library

    • In this Google Maps Distance Calculator (It is clear from the name) we need to calculate the distance between two coordinates from the map. And for this I will be using this library. So first we have to add this library to our gradle.build dependencies block.
    • We also need to send an HttpRequest to get the path between two coordinates. For this I will be using Volley Library.
    • So go inside your gradle.build file and add the following dependencies.
    • Now come to activity_maps.xml and write the following code. It will create our layout.
    • As you can see we have only 3 buttons on the layout and a fragment to display maps. The buttons are to set the coordinates and calculate distance. When the user will calculate the distance we will also show the path between the coordinates.
    • Now come to MapsActivity.java and write the following code.
    • The above code is already explained in my previous google maps tutorial. Till here we are able to get the two coordinates from the map. The final things we need to do for our Google Maps Distance Calculator App is:
      • We have to calculate the distance between the coordinates.
      • We have to draw a path between the coordinates.
    • As we are using Google Maps API Utility Library, calculating distance is extremely easy. We can use the following code to calculate the distance between coordinates.
    • To draw the path between the coordinates we need to know the path. This is a little difficult as we need to call the Google Maps Direction API. For this first we will create our request URL. For this we can use the following code. (Replace SERVER-KEY with your Server Key that you created in your Google Developer’s Account).
    • The above method would give us a URL as a string. We need to send a get request the the URL and in return (if successful) we will get JSON.
    • To send the request we will use volley.
    • These two methods will draw the route on the map. I got this from Stack Overflow.

    (result >> 1) : (result >> 1));

    (result >> 1) : (result >> 1));

    • The final code of our MapsActivity.java for this Google Maps Distance Calculator would be.

    (result >> 1) : (result >> 1));

    (result >> 1) : (result >> 1));

    • Lastly for this Google Maps Distance Calculator you need to add the following permissions to your AndroidManifest.xml

    • Now thats all, just run your Google Maps Distance Calculator(Use a real device).

    Google Maps Distance Calculator

    • Bingo! Our Google Maps Distance Calculator is Working absolutely fine. You can get my source code from below.

    Thats all for this Google Maps Distance Calculator.Please share this post if you found it helpful to support us. And also feel free to ask if having any query regarding this Google Maps Distance Calculator. Thank You 🙂

    Hi, my name is Belal Khan and I am a Google Developers Expert (GDE) for Android. The passion of teaching made me create this blog. If you are an Android Developer, or you are learning about Android Development, then I can help you a lot with Simplified Coding.

    Checkout these tutorials as well:

    32 thoughts on “Google Maps Distance Calculator using Google Maps API”

    Hi Bilal just tell me why you use Uri.parse(“android-app://net.simplifiedcoding.googlemapsdistancecalc/http/host/path”);

    And when i am running the code then it is not working app gets crash.

    And also this site’s captcha also not work first time.It always shows error and second time works fine.

    Oh that is generated automatically.. I just forget to remove it.. It will also work without that.. we need only to connect with the api with googleApiClient.connect(); on onStart and we are disconnecting it in on stop()..
    check the previous tutorial
    https://www.simplifiedcoding.net/android-google-maps-tutorial-google-maps-android-api/

    Sorry now the app is working absolutely fine but when i am dragging marker from current location to any other point then it is not calculating distance always showing 0.0 meter And what is the use of set from and set to button?when clicks on both button only showing toast message From Set and To Set.

    Check your coordinates are getting initialized properly or not.. you have to use the methods onMarkerDragStart and onMarkerDragEnd

    So what should i have to write inside onMarkerDragStart().

    I have the same problem can any body help us please ??

    A question, please…How I get a Server-Key from Google Developers Console? I have my Api key, but this error appear “This IP, site or mobile application is not authorized to use this API key”, please help me.

    thanks, let me try it now 🙂

    when I run this app. App crash , no output show. what I do for this?

    How to implement this same thing without maps.
    I mean the app should the distance between the two areas
    It should have two text fields. one is from address and other is to address.
    as the user enters the area names it show the distance between the areas.

    How to implement that?

    Hey i am facing this error while implementing this task.

    Process: com.example.mayankacharya.dataparsingtutorial, PID: 7553
    java.lang.RuntimeException: Unable to start activity ComponentInfo: java.lang.NullPointerException: null reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
    Caused by: java.lang.NullPointerException: null reference
    at com.google.android.gms.common.internal.zzx.zzz(Unknown Source)
    at com.google.android.gms.appindexing.Thing$Builder.setUrl(Unknown Source)
    at com.google.android.gms.appindexing.Action.newAction(Unknown Source)
    at com.google.android.gms.appindexing.Action.newAction(Unknown Source)
    at com.example.mayankacharya.dataparsingtutorial.MapsActivity2.onStart(MapsActivity2.java:129)
    at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1237)
    at android.app.Activity.performStart(Activity.java:6253)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

    Bhai my app is running fine but there is one problem that it is not drawing the path from source to destination.
    Please! Help.

    Hi @Eduardo Caballero and @Shubham

    April 3, 2016 at ,maybe you have not unable Map Distance API for your project check here Google API Console

    Thank you for the actionable content. Very useful.

    Great tutorial, Thank you..

    Hi. grate tutorials!
    i have followed your code but i still get problem like this :

    1. the drawer map not appears
    2. The distance shown 0.0 meters
    3. The marker of destination not appears too.

    where i should set the destination latitude?. On your code just in button SET TO “toLatitude = latitude” it gives toLatitude = current position value. not my destination latitude.

    could you replay my problem and help me, please.

    Thanks very much for the tutorial.

    we want one program like etaxi

    Hi i have a one doubt actually google maps user want to click the particular location how to display the that particular latitude and longitude display
    EX
    when I have click the Chennai means it display the latitude and longitude display not hard coded in the value for latitude and longitude how to implement it please help me…………

    Hey, The app is working almost perfect, the only issue that I have is with the Drawing of the Map, it doesn’t do it.
    The distance is calculated correctly and everything, but the route it just doesn’t show up. Does anyone have this problem too?

    SphericalUtil.computeDistanceBetween() is used to calculate STRAIGHT LINE distance between two latlng points.. it doesnt calculate actual path distance with legs and turns..however, direction API does return actual path distance in json format, u just need to parse that as well..

    polyline not working otherwise app working help me.. sir!

    I am getting these errer :
    java.lang.RuntimeException: Unable to start activity ComponentInfo: java.lang.IllegalArgumentException: AppIndex: The android-app URI host must match the package name and follow the format android-app:////. Provided URI: android-app://net.simplifiedcoding.googlemapsdistancecalc/http/host/path
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2426)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5443)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
    What should i do?Can you please help

    Polyline not showing on map – Everything else works great.

    Possible Error in Code “try <>”??

    I’ve applied my own API to build & in the code for “urlString.append” (used same API #)

    Program displays the “Toast” msg, goes to “try”, but never completes the “try”, so this is where the problem is,
    it does go into the “catch (JSONException e) <>”:
    Toast.makeText(this,String.valueOf(distance+” Meters”),Toast.LENGTH_SHORT).show();

    try <
    //Parsing json
    final JSONObject json = new JSONObject(result);
    JSONArray routeArray = json.getJSONArray(“routes”);
    JSONObject routes = routeArray.getJSONObject(0);
    JSONObject overviewPolylines = routes.getJSONObject(“overview_polyline”);
    String encodedString = overviewPolylines.getString(“points”);
    List list = decodePoly(encodedString);
    Polyline line = mMap.addPolyline(new PolylineOptions()
    .addAll(list)
    .width(20)
    .color(Color.RED)
    .geodesic(true)
    );
    >
    catch (JSONException e) <
    >

    Any idea for why the “try<>” is not getting completed and kicks out the “catch () <>”?

    Thanks in advance…….

    P.S.
    Thanks for all your great Tutorials on Google API Maps…………

    UPDATE – APP IS WORKING 100%

    Service Key Needed To Be Added.

    I seen your comment about the “Service Key” from Google API, but the documentation at Google’s site
    was unclear about how to obtain the Service Key, I had originally just used my API Key. Once I obtained the
    Sevice Key and replaced your Service Key with mine, the “Polyline” showed on the map.

    Thanks again for the tutorials, they’re great…………

    hello can i know how to obtain the service key?

    Источник

    Читайте также:  Риа новости для андроида
    Оцените статью