I have been coding around with Google Geocoding until I found out that the Geocoding API may only be used in conjunction with a Google map. That is inconvenient because I don't need to display a map. So I switched to Geonames which is awesome!
I get the latitude and longitude of an address and add them to my database.
The code below is Jquery for a text input where users add their city/town and an auto-complete appears presuming the city they are typing. It works great but I also want to add the latitude and longitude of their city in 2 hidden form fields for sending to the database.
How is it possible to retrieve those coordinates from Geonames?
$(function() {
function log( message ) {
$( "<div/>" ).text( message ).prependTo( "#log" );
$( "#log" ).attr( "scrollTop", 0 );
}
$( "#city" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "http://ws.geonames.org/searchJSON",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function( data ) {
response( $.map( data.geonames, function( item ) {
return {
label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
value: item.name开发者_运维百科
}
}));
}
});
},
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
});
The lat
& lng
are being returned; see this test request:
http://api.geonames.org/searchJSON?style=full&maxRows=12&name_startsWith=romse&username=demo
It is in the structure below so you just need to access it:
{ "geonames" : [ {
"adminCode1" : "ENG",
<SNIP>
"geonameId" : 2639189,
"lat" : 50.989057046475203,
"lng" : -1.4998912811279297
精彩评论