Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
135
rated 0 times [  138] [ 3]  / answers: 1 / hits: 23086  / 14 Years ago, thu, january 13, 2011, 12:00:00

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>

More From » json

 Answers
39

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:



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

[#94236] Wednesday, January 12, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaelyn

Total Points: 619
Total Questions: 102
Total Answers: 104

Location: Honduras
Member since Sun, Dec 26, 2021
2 Years ago
;