Distance between two JavaScript marker

0

Good morning. I have this code that receives lat start, long start, lat end, long end and it generates a map with two marker and then shows how to get to that point by DRIVING.

<?php 
$latitudInicio = $_GET['latitudInicio'];
$longitudInicio = $_GET['longitudInicio'];
$latitudFin = $_GET['latitudFin'];
$longitudFin = $_GET['longitudFin'];
?>
<!DOCTYPE html>
<html>
 <head>
   </head>
   <body>
   <div id="map" style="width: 100%; height: 700px;"></div>
   <script>
   function initMap() {
    var inicio = {lat: <?php echo $latitudInicio ?>, lng: <?php echo $longitudInicio ?>};
    var fin = {lat: <?php echo $latitudFin ?>, lng: <?php echo $longitudFin ?>};




    var map = new google.maps.Map(document.getElementById('map'), {
      center: inicio,
      zoom: 7
    });

    var inicioMarker = new google.maps.Marker({
      position: inicio,
      map: map,
      title: '<?php echo $latitudInicio ?> <?php echo $longitudInicio ?>'
    });
    var finMarker = new google.maps.Marker({
      position: fin,
      map: map,
      title: '<?php echo $latitudFin ?> <?php echo $longitudFin ?>'
    });


    var directionsDisplay = new google.maps.DirectionsRenderer({
      map: map,
      suppressMarkers: true
    });

    // Set destination, origin and travel mode.
    var request = {
      destination: fin,
      origin: inicio,
      travelMode: 'DRIVING'
    };




    // Pass the directions request to the directions service.
    var directionsService = new google.maps.DirectionsService();
    directionsService.route(request, function(response, status) {
      if (status == 'OK') {
        // Display the route on the map.
        directionsDisplay.setDirections(response);
      }
    });
  }

</script>
<script src="https://maps.googleapis.com/maps/api/js?
key=API_KEY&callback=initMap"
    async defer></script>
  </body>
</html>

Now what I need is to show in a label, input text, etc, the distance between those two marker. Searching in the google documentation I come to this:

link

Here what happens to me in a direction that generates a json with the two directions that I can pass by parameter and there if I see the time it takes between the points. Now, I do not understand how to use it or what I have to do with that code to be able to show it, do they give me a hand? Thank you very much!

{
  "destination_addresses" : [ "Nueva York, EE. UU." ],
   "origin_addresses" : [ "Washington D. C., Distrito de Columbia, EE. UU." ],
  "rows" : [
     {
     "elements" : [
        {
           "distance" : {
              "text" : "225 mi",
              "value" : 361720
           },
           "duration" : {
              "text" : "3h 50 min",
              "value" : 13794
           },
           "status" : "OK"
        }
     ]
  }
    ],
   "status" : "OK"
}
    
asked by Juan 13.09.2017 в 15:42
source

2 answers

1

So you can get the distance in JSON dynamically you have to make a call to the URL that Google Maps gives you, there are different ways to do this, one way to do it in JavaScript code would be using XMLHttpRequest .

I'll give you an example, remember that you must change your access code to the Google API, and also change the coordinates as required:

var API_KEY = "TU LLAVE DE ACCESO A GOOGLE MAPS API"

var latOrigen = "40.6655101"
var lonOrigen = "-73.8918896"
var latDestino = "40.6905615"
var lonDestino = "-73.9976592"

var distanciaURL = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=" + latOrigen + "," + lonOrigen + "&destinations=" + latDestino + "," + lonDestino + "&key=" + API_KEY

var request = new XMLHttpRequest();

request.onreadystatechange = function() {
if (request.readyState === 4 && request.state == 200) { //200 significa que la petición a Google fue correcta
  var respuesta = JSON.parse(request.responseText)
  if (respuesta) {
    var distancia = respuesta.rows[0].elements[0].distance.text
    if (distancia) {
      document.getElementById("span_distancia").innerText = distancia
    } else {
      console.log("Error al obtener el valor de la distancia")
    }
  } else {
    console.log("Error al convertir la respuesta obtenida de Google")
  }
} else {
  console.log("Error al pedir la distancia entre dos puntos a Google")
}
}
request.open('GET', distanciaURL, true);
request.send();
Distancia entre los puntos: <span id="span_distancia"></span>
    
answered by 13.09.2017 в 18:07
0

I was finally able to do it, but I had to change from JS to Web Service. I leave the code:

<?php 
    $direccionInicio = !empty($_GET['direccionInicio']) ? urlencode($_GET['direccionInicio']) : null;
    $direccionFin = !empty($_GET['direccionFin']) ? urlencode($_GET['direccionFin']) : null;
    $urlApi = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=".$direccionInicio."&destinations=".$direccionFin."&key=API_KEY";
    $result = file_get_contents($urlApi);
    $data = json_decode($result, true);
    $millas =  $data['rows'][0]['elements'][0]['distance']['text'];
    $millasKm = round(($millas * 1.60934),2);
    $distancia = $data['rows'][0]['elements'][0]['duration']['text'];
    ?>
    Direccion de inicio: <?php echo $direccionInicio; ?><br>
    Direccion de fin: <?php echo $direccionFin; ?><br>
    Distancia entre los dos puntos: <?php echo $millasKm." Km";?><br>
    Tiempo entre los dos puntos: <?php echo $distancia;?><br>
    
answered by 13.09.2017 в 19:01