开发者

Getting a json response into variable

开发者 https://www.devze.com 2023-02-27 01:58 出处:网络
I am trying to use the google geocoder api to get the longitude and latitude of an address to use in a map-making app.

I am trying to use the google geocoder api to get the longitude and latitude of an address to use in a map-making app.

how do i get the data from a geocode request (for instance:

"http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true" is the example used on the api site) into a variable in my script so I can extract data from it? or is it possible to开发者_C百科 extract data another way?

Thanks!! :)


Ok, so first things first... you're looking at using JavaScript, not Java.

I'm going to steer you in a bit of a different direction. You won't need JSON.

I'm assuming you're using the google maps javascript api? If not you should be.

To utilize the google maps api you'll need to include this <script> tag in the <head> section of your web page:

<script src="http://maps.google.com/maps/api/js?sensor=false"></script>

Add a second <script> tag to the <head> like so:

<script type="text/javascript">     
   var geocoder;

   function Geocode(address){
      geocoder = new google.maps.Geocoder();

      geocoder.geocode({ 'address': address }, function (results, status) {
         if (status == google.maps.GeocoderStatus.OK) {
            console.log("Latitude: " + results[0].geometry.location.lat());
            console.log("Longitude: " + results[0].geometry.location.lng());
         }
         else {
            console.log("Geocoding failed: " + status);
         }
      });
   } 
</script>

The above Geocode() function accepts an address as a parameter. It then makes a Geocode request via the Geocoder Object from the Google Maps API and passes the response from the Geocoder object into the callback function (function(results,status){...}). For a full reference of what the 'results' parameter being passed into the callback function contains look here

Hope this helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消