I am able to get get full address from current latitude and longitude. but how can I get only city name from full address. this is my code.
var geocoder;
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(latitude, longitude);
//alert("Else loop" + latlng);
geocoder.geocode({
'latLng': latlng
}, function(results, status) {
//alert("Else loop1");
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
var add = results[0].formatted_address;
alert("Full address is: " + add);
} else {
alert("address not found");
}
} else {
//document.getElementById("location").innerHTML="Geocoder failed due to: " + status;
//alert("Geocoder failed due to: " + status);
}
});
var geocoder;
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(latitude, longitude);
geocoder.geocode(
{'latLng': latlng},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
var add= results[0].formatted_address ;
var value=add.split(",");
count=value.length;
country=value[count-1];
state=value[count-2];
city=value[count-3];
alert("city name is: " + city);
}
else {
alert("address not found");
}
}
else {
alert("Geocoder failed due to: " + status);
}
}
);
Split the full address with "," as delimiter and get the city name..
Clean example to get location from lat and lang and parsing result. based on Google Reverse Geocoding
var geocodingAPI = "https://maps.googleapis.com/maps/api/geocode/json?latlng=23.714224,78.961452&key=YOUR_SERVER_API_KEY";
$.getJSON(geocodingAPI, function (json) {
if (json.status == "OK") {
//Check result 0
var result = json.results[0];
//look for locality tag and administrative_area_level_1
var city = "";
var state = "";
for (var i = 0, len = result.address_components.length; i < len; i++) {
var ac = result.address_components[i];
if (ac.types.indexOf("administrative_area_level_1") >= 0) state = ac.short_name;
}
if (state != '') {
console.log("Hello to you out there in " + city + ", " + state + "!");
}
}
});
You can find documentation here :
https://developers.google.com/maps/documentation/geocoding/?hl=fr#ReverseGeocoding
But you can see in your "results" which item is the city without spliting the object.
So you can do :
country=results[0]['address_components'][6].long_name;
state=results[0]['address_components'][5].long_name;
city=results[0]['address_components'][4].long_name;
Be carefull, the numbers "4,5,6" can change by the country. So it safier to test like that :
Getting street,city and country by reverse geocoding using google
Take a look at Google Reverse Geocoding
http://maps.google.com/maps/api/geocode/xml?latlng=YourLatitude,YourLongitude&sensor=false&key=API_KEY
This is already asked here
This is how I I'm doing it. Was afraid to use a comma delimiter.
function ReverseGeoToCity(lat, lng, callback) {
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
var properName = ", ";
for(i=0; i<results[1].address_components.length; i++){
if (results[1].address_components[i].types[0] == "locality")
properName = results[1].address_components[i].short_name + properName;
if (results[1].address_components[i].types[0] == "administrative_area_level_1")
properName += results[1].address_components[i].short_name;
}
callback(properName);
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
}
Below code will help you for get city name From latitude and longitude:
var url = "https://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+long+"&key=KEY_HERE&sensor=false";
$.get(url, function(data) {
var results = data.results;
if (data.status === 'OK')
{
//console.log(JSON.stringify(results));
if (results[0])
{
var city = "";
var address_components = results[0].address_components;
for (var i = 0; i < address_components.length; i++)
{ state = address_components[i].long_name;
}
if (address_components[i].types[0] === "locality" && address_components[i].types[1] === "political" ) {
city = address_components[i].long_name;
}
}
alert("CITY : " + city );
}
else
{
window.alert('No results found');
}
}
else
{
window.alert('Geocoder failed due to: ' + status);
}
});
Related
I am getting the following error while trying to fetch current location using Google Maps API.
Error:
Geocoder failed
I am providing my code below.
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
function getDefaultLocation(){
setTimeout(function(){
var geocoder='';
geocoder = new google.maps.Geocoder();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
codeLatLng(lat, lng)
}
function errorFunction(){
console.log("Geocoder failed");
}
function codeLatLng(lat, lng){
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if(status == google.maps.GeocoderStatus.OK){
if (results[1]) {
var indice=0;
for (var j=0; j<results.length; j++){
if (results[j].types[0]=='locality'){
indice=j;
break;
}
for (var i=0; i<results[j].address_components.length; i++){
if (results[j].address_components[i].types[0] == "locality") {
city = results[j].address_components[i];
}
if(results[j].address_components[i].types[0] == "administrative_area_level_1"){
region = results[j].address_components[i];
}
if (results[j].address_components[i].types[0] == "country"){
country = results[j].address_components[i];
}
if(results[j].address_components[i].types[0] == "route"){
locality=results[j].address_components[i];
}
}
}
// console.log('final result',city.long_name,region.long_name,country.long_name,locality.long_name);
var city=city.long_name;
var country=country.long_name;
var locality=locality.long_name;
document.getElementById('bindCon').innerHTML=country; document.getElementById('bindCit').innerHTML=city; document.getElementById('bindloc').innerHTML=locality;
}else{
console.log("No results found");
}
}else{
console.log("Geocoder failed due to: " + status);
}
})
}
},5000);
}
The above code is working properly in localhost but while putting this into my testing site (http://xxxx.com) the above error is coming. Here I need to fetch all the required data.
I had implemented geolocation , wherein browser gets location of user.
In this code i'm getting geolocation of user through browser ,but it display location using javascript alert message.
I just want to pass alert message value to label or hiddenfield in ASP.Net & doesn't want to run alert message
My javascript code as follows.
<script type="text/javascript">
var geocoder;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
//Get the latitude and the longitude;
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
codeLatLng(lat, lng)
}
function errorFunction() {
alert("Geocoder failed");
}
function initialize() {
geocoder = new google.maps.Geocoder();
}
function codeLatLng(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results)
if (results[1]) {
//formatted address
alert(results[0].formatted_address)
//find country name
for (var i = 0; i < results[0].address_components.length; i++) {
for (var b = 0; b < results[0].address_components[i].types.length; b++) {
//there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
if (results[0].address_components[i].types[b] == "administrative_area_level_1") {
//this is the object you are looking for
city = results[0].address_components[i];
break;
}
}
}
//city data
alert(city.short_name + " " + city.long_name)
document.getElementById('<%=Label1.ClientID %>').innerHTML = city;
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
</script>
If you want to store the value in a hidden field replace
alert(results[0].formatted_address)
with
//hdnField is the ID of your asp:HiddenField object
var hiddenField = document.getElementById("<%= hdnField.ClientID %>")
hiddenField.value = results[0].formatted_address;
I have some latitudes and longitudes i want to find out their addresses.
function OnSuccess(response) {
showLatLng(0, JSON.parse(response.d).Table, JSON.parse(response.d).Table.length);
}
Where JSON.parse(response.d).Table contains the result set.
function showLatLng(index, resultSet, totalLen) {
var lat = resultSet[index].x;
var lng = resultSet[index].y;
var latlng = new google.maps.LatLng(lat, lng);
new google.maps.Geocoder().geocode({ 'latLng': latlng },
function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
var z = " <tr>" +
"<td>" + results[0].formatted_address + "</td>" +
"</tr>";
$("#result").append(z);
if (index < totalLen) {
showLatLng(index + 1, resultSet, totalLen);
}
}
}
});
}
This code is working only 4 to 5 times then stops and no error in firebug.
Please give me a better way to do this.
EDIT:
Lucas You are absolutely right.
Previously I have used loop with timeout as below
$.each(JSON.parse(response.d).Table, function (index, value) {
setTimeout(function () {
showLatLng(index , value.x, value.y);
}, (index + 1) * 7000);
});
But for some reason (because I think it is working on async call) it is skipping some results.
pass Latitude and Longitude value to script
function GetAddress() {
var lat = parseFloat(document.getElementById("txtLatitude").value);
var lng = parseFloat(document.getElementById("txtLongitude").value);
var latlng = new google.maps.LatLng(lat, lng);
var geocoder = geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
alert("Location: " + results[1].formatted_address);
}
}
});
}
I have this function that should return the country starting from the latitude and longitude and assign it to a global variable declare outside the function. I know that the a in Ajax stand for asynchronous and I have read every single answer on stackoverflow but I can't fix it.
function getLatLongDetail(myLatlng) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'latLng': myLatlng },
function (results, status) {
var country = "";
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
for (var i = 0; i < results[0].address_components.length; i++) {
var addr = results[0].address_components[i];
// check if this entry in address_components has a type of country
if (addr.types[0] == 'country')
country = addr.long_name;
}
}
return country; // this doesn't work
}
}
});
}
var Country = getLatLongDetail(myLatlng);
alert(Country);// undefined
I know there are hundreds of questions about callback function but none of them worked for me.
Finally I made it! Here the code:
function getLatLongDetail(myLatlng, fn) {
var geocoder = new google.maps.Geocoder();
var country = "";
var city = "";
var address = "";
var zip = "";
var state = "";
geocoder.geocode({ 'latLng': myLatlng },
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
for (var i = 0; i < results[0].address_components.length; i++) {
var addr = results[0].address_components[i];
// check if this entry in address_components has a type of country
if (addr.types[0] == 'country')
country = addr.long_name;
else if (addr.types[0] == ['locality']) // City
city = addr.long_name;
else if (addr.types[0] == 'street_address') // address 1
address = address + addr.long_name;
else if (addr.types[0] == 'establishment')
address = address + addr.long_name;
else if (addr.types[0] == 'route') // address 2
address = address + addr.long_name;
else if (addr.types[0] == 'postal_code') // Zip
zip = addr.short_name;
else if (addr.types[0] == ['administrative_area_level_1']) // State
state = addr.long_name;
}
}
fn(country,city, address, zip, state);
}
});
}
var mCountry; //global variable to store the country
vat mCity; //global variable to store the city
getLatLongDetail(event.latLng, function(country,city, address, zip, state){
mCountry = country; // now mCountry store the value from getLatLongDetail so I can save it in the database
mCity = city;
alert(address + zip + state);
});
Ive tried several methods to get get a visitors country location using geolocation method but im stil at no avail.
Could someone help atall as I'd like to get a visitors country and write it to a database using ajax.
my current code
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script>
var geocoder;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
//Get the latitude and the longitude;
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
codeLatLng(lat, lng)
}
function errorFunction(){
alert("Geocoder failed");
}
function initialize() {
geocoder = new google.maps.Geocoder();
}
function codeLatLng(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results)
var country = results[7].formatted_address;
$('.location').text(country);
var dataStrings = 'email=<?php echo $userid;?>&location='+ country;
console.log(dataStrinsg);
$.ajax({
type: "POST",
url: "location-update.php",
data: dataStrings,
success: function() {
location.reload();
}
});
return false;
if (results[1]) {
//formatted address
// alert(results[0].formatted_address)
//find country name
for (var i=0; i<results[0].address_components.length; i++) {
for (var b=0;b<results[0].address_components[i].types.length;b++) {
//there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
if (results[0].address_components[i].types[b] == "administrative_area_level_1") {
//this is the object you are looking for
city= results[0].address_components[i];
break;
}
}
}
//city data
alert(city.short_name + " " + city.long_name)
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}</script>
Assuming that you call initalize() before the geocoding(otherwise geocode will be undefined):
You're accessing results[7] here:
var country = results[7].formatted_address;
...but there is no guarantee that results[7] exists.