Json geocoding google api

Here is a code that gets latitude and duration when entering location.I believe that my code is in accordance with my knowledge.but, I get a blank page after entering the 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> 
+4
source share
2 answers

You are trying to use JSONP here.

Jsonp

If the URL contains the string "callback =?" (or similarly, as defined by the server-side API), requests> are processed as JSONP. See the discussion of jsonp data type in $ .ajax () for more details.

Important. Starting with jQuery 1.4, if the JSON file contains a syntax error, the request usually fails.

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

But the URL you are calling returns plain JSON, so the parsing fails with the syntax error and getJSON fails.

Now, when you try to change the geocode URL to use JSONP, you get a 404 error, since Google recently removed JSONP support:

In short:
You cannot just use the geocode api from a JavaScript browser, you will have to add a proxy script to your server.

And even if the request works, there is still an error in your code:

json.results is an array of results, so it does not have a geometry property.

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

 json.results[9].geometry.location.lng 
+7
source

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

 var myAddressQuery = 'OJ 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

+15
source

Source: https://habr.com/ru/post/1335419/


All Articles