开发者

json with google geocoding api

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){

             $('#result开发者_JAVA百科s').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>


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


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
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜