json with google geocoding api

岁酱吖の 提交于 2019-11-27 06:20:08

问题


Here is code which gets latitude and longitute when entered a location.I believe that my code right according to my knowledge.but i get a blank page after entering a place.

Here is the code:

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){

    var url="http://maps.googleapis.com/maps/api/geocode/json?address=";
    var query;
    var sensor="&sensor=false";
    var callback="&callback=?";


    $("button").click(function(){
          query=$("#query").val();
          $.getJSON(url+query+sensor+callback,function(json){

             $('#results').append('<p>Latitude : ' + json.results.geometry.location.lat+ '</p>');
             $('#results').append('<p>Longitude: ' + json.results.geometry.location.lng+ '</p>');

});


    });
});


</script>

</head>
<body>

<input type="text" id="query" /><button>Get Coordinates</button>
<div id="results"></div>

</body>
</html>

回答1:


You're trying to use JSONP here.

JSONP

If the URL includes the string "callback=?" (or similar, as defined by the server-side API), the request > is treated as JSONP instead. See the discussion of the jsonp data type in $.ajax() for more details.

Important: As of jQuery 1.4, if the JSON file contains a syntax error, the request will usually fail silently.

See: http://api.jquery.com/jQuery.getJSON/

But the URL you're calling returns plain JSON, so the parsing fails with a syntax error and getJSON fails silently.

Now when you try to change the geocode URL to use JSONP, you get a 404 error since Google has removed support for JSONP quite a while ago:

  • http://code.google.com/p/gmaps-api-issues/issues/detail?id=1872
  • http://blog.mikecouturier.com/2009/11/jsonp-and-google-maps-api-geocoder-not.html

In short:
You cannot simply use the geocode api from Browser JavaScript anymore, you'll have to add a proxy script on your server.

And even if the request would work, your code still has a bug in it:

json.results is an array of results, so it has no geometry property.

You have to access the first element of the array in order to get to the actual object that has the geometry property:

json.results[9].geometry.location.lng



回答2:


In Google Maps Javascript V3 you can access the geocoding service using the google.maps.Geocoder class.

var myAddressQuery = 'O. J. Brochs g 16a, Bergen';
var geocoder = new google.maps.Geocoder(); 
geocoder.geocode(
    { address : myAddressQuery, 
      region: 'no' 
    }, function(results, status){
      // result contains an array of hits.
});

https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple



来源:https://stackoverflow.com/questions/4681928/json-with-google-geocoding-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!