0

How to decode the URL in javascript?

<?php $url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=London&destinations=drove&mode=driving&language=en&sensor=false";
        $data = file_get_contents($url);
        $data = utf8_decode($data);
        $obj = json_decode($data);

        echo($obj->rows[0]->elements[0]->distance->text); //km
    ?>

I want to do the same thing with javascript.

  • nit pick: you're not decoding the url. you're decoding the content the url points at. – Marc B Jul 28 '15 at 17:57
  • Not exactly sure what you're intentions are here -- you want to perform the equivalent of *all* of the code you posted in pure JavaScript? If so, I would suggest simply making an AJAX request to the PHP file you already have. Or, look into jQuery and its `$.getJSON` method. – Cᴏʀʏ Jul 28 '15 at 17:57
  • { "destination_addresses" : [ "Drove, 52372 Kreuzau, Germany" ], "origin_addresses" : [ "London, UK" ], "rows" : [ { "elements" : [ { "distance" : { "text" : "570 km", "value" : 570075 }, "duration" : { "text" : "6 hours 28 mins", "value" : 23309 }, "status" : "OK" } ] } ], "status" : "OK" } I just want to get this data but in javascript variables. – Muhammad Sohaib Roomi Jul 28 '15 at 18:01
  • An extremely relevant question: http://stackoverflow.com/questions/2445276/how-to-post-data-in-php-using-file-get-contents – aug Jul 28 '15 at 18:03
  • but i want this in javascript – Muhammad Sohaib Roomi Jul 28 '15 at 18:05
  • If you are doing it in Javascript, why not use the [Google Maps Javascript API v3 DistanceMatrix Service](https://developers.google.com/maps/documentation/javascript/distancematrix)? – geocodezip Jul 28 '15 at 19:08

1 Answers1

0

In javascript you can use JSON.parse(yourdata);

 var jsonData =  JSON.parse(data);
 alert(jsonData.rows[0].elements[0].distance_test;
scaisEdge
  • 124,973
  • 10
  • 73
  • 87