简体   繁体   中英

Google Distance Matrix API no output

I'm trying to use Distance Matrix API to calculate the distance between 2 places. Because this is the first time I'm trying to use this API I litterally copied the code I found on the Google Documentation's page and pasted on my page. But, I can't see any kind of output and I don't know why. This is my page

And this is the source :

<!DOCTYPE html> 
<html> 
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">

<!-- Google Api -->
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDDMkiaVfr1y0QCsx_qUsJKIBAWpkyXZrY&sensor=false">
</script>

<script type="text/javascript">
var origin1 = new google.maps.LatLng(55.930385, -3.118425);
var origin2 = "Greenwich, England";
var destinationA = "Stockholm, Sweden";
var destinationB = new google.maps.LatLng(50.087692, 14.421150);

var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
  {
    origins: [origin1, origin2],
    destinations: [destinationA, destinationB],
    travelMode: google.maps.TravelMode.DRIVING,
    avoidHighways: false,
    avoidTolls: false
  }, callback);

function callback(response, status) {
  if (status == google.maps.DistanceMatrixStatus.OK) 
  {
    var origins = response.originAddresses;
    var destinations = response.destinationAddresses;
    document.writeln(response.originAddresses[1]);    
  }

  else {
    document.writeln("error");

       }
  }  

</script>
</html> 

Ok so I have no idea why that doesn't work. First, I recommend you use jQuery . You can find it here.

First, wrap your code in a $(document).ready() function, so that it is executed when the page is ready ,

$(document).ready(function() {
  // Everything in your original script block
  var origin1 = new google.maps.LatLng(55.930385, -3.118425);
  // etc etc      
});

Secondly, it's alot easier writing to the document when you know where you're writing to. Make a div that will hold your location data.

<body>
<div id="location"/>
</body>

Thirdly, when you have your location from Google, change the text in your div to match:

$("#location").text(response.originAddresses[1]);

Dealing with the document without jQuery is a nightmare, I highly recommend using this library.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM