Find address recursively from latitudes and longitudes in google map api - javascript

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);
}
}
});
}

Related

In my geocoder geocode callback, how do I determine which request the result corresponds to?

I'm looping through about 60 addresses to get them geocoded for use on a Google Map. My callback (below) seems to work well for collecting the locations, but I need to know how to relate them to the address objects I'm looping through. I can't find anything in the geocode response that tells me which of my requests it 'came from.'
Is there a way to do that?
This is my function:
geocode() {
var lv_location;
var geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({'address' : this.address},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
// what data in results can be used to relate the location to the address?
lv_location = results[0].geometry.location;
}
markerCounter++;
if (markerCounter >= 60) finishSurnames();
});
}
In JavaScript you can use Immediately-invoked function expression that will create a function scope also known as closure. You should change your function to something similar to
geocode() {
var lv_location;
var geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({'address' : this.address}, (function(originalAddress){
return function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
// what data in results can be used to relate the location to the address?
//You can use the originalAddress variable here to relate result to request
lv_location = results[0].geometry.location;
}
markerCounter++;
if (markerCounter >= 60) finishSurnames();
};
})(this.address));
}
}
Have a look at my example, it geocodes 3 addresses and print in console result and corresponding request string
var addresses = [
'av Diagonal 197, Barcelona',
'av Lucas Vega 53, San Cristobal de La Laguna',
'Metrologichna 14, Kiev'
];
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: {lat: -34.397, lng: 150.644}
});
var geocoder = new google.maps.Geocoder();
addresses.forEach( function(address) {
geocode(geocoder, address);
});
}
function geocode(geocoder, address) {
geocoder.geocode({'address': address}, (function(originalAddress) {
return function(results, status) {
if (status === 'OK') {
console.log("Search: " + originalAddress + "->" + results[0].geometry.location.toString());
} else {
console.log("Search: " + originalAddress + "->" + status);
}
};
})(address));
}
#map {
height: 100%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?v=3&key=AIzaSyDztlrk_3CnzGHo7CFvLFqE_2bUKEq1JEU&callback=initMap">
</script>
I hope this helps!

How to get current location name from longitude and latitude?

I'm using this code to get the current location of the user through google maps api and i am getting the location in the form of latitude and longitudes and getting the location in LatLng variable.
But after that when I am converting the latitude and longitude to an address then its not working.
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (p){
var LatLng = new google.maps.LatLng(p.coords.latitude,p.coords.longitude);
alert(LatLng);
alert(p.coords.latitude);
alert(p.coords.longitude);
var mapOptions = {
center: LatLng,
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'LatLng': LatLng }, function (results, status){
alert(geocoder);
if (status == google.maps.GeocoderStatus.OK){
if (results[1]){
alert("Location: " + results[1].formatted_address);
}
}
});
Firstly as the commentator Parker told, jsp and java tags are irrelevant for your post. I removed it.
You should do the reverse geocoding. The process of doing the converse, translating a location on the map into a human-readable address, is known as reverse geocoding.
Please refer the below google map url for Reverse Geocoding.
See the below snippet of mapping lat & lan to location,
var latlng = {lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1])};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === 'OK') {
if (results[0]) {
map.setZoom(11);
var marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
Let me know if it helps.
$(document).ready(function() {
var currgeocoder;
//Set geo location of lat and long
navigator.geolocation.getCurrentPosition(function(position, html5Error) {
geo_loc = processGeolocationResult(position);
currLatLong = geo_loc.split(",");
initializeCurrent(currLatLong[0], currLatLong[1]);
});
//Get geo location result
function processGeolocationResult(position) {
html5Lat = position.coords.latitude; //Get latitude
html5Lon = position.coords.longitude; //Get longitude
html5TimeStamp = position.timestamp; //Get timestamp
html5Accuracy = position.coords.accuracy; //Get accuracy in meters
return (html5Lat).toFixed(8) + ", " + (html5Lon).toFixed(8);
}
//Check value is present or not & call google api function
function initializeCurrent(latcurr, longcurr) {
currgeocoder = new google.maps.Geocoder();
console.log(latcurr + "-- ######## --" + longcurr);
if (latcurr != '' && longcurr != '') {
var myLatlng = new google.maps.LatLng(latcurr, longcurr);
return getCurrentAddress(myLatlng);
}
}
//Get current address
function getCurrentAddress(location) {
currgeocoder.geocode({
'location': location
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results[0]);
$("#address").html(results[0].formatted_address);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
});
</script>

How to get city name from latitude and longitude in phone gap?

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);
}
});

How to get address from lat and lng?

I have two set of lat and lng.
I want both address and stored in some variable:
var geocoder = new google.maps.Geocoder();
for(var i=0; i<json_devices.length; i++)
{
var lat = json_devices[i].latitude;
var lng = json_devices[i].longitude;
console.log(lat);
console.log(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]) {
address=results[1].formatted_address;
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
console.log(address);
}
In this, lat & lan get correctly. But address are not stored in variable. What is the mistake?
I am using this method and it is working perfect for me.
Please have a look on it.
public String getAddressFromLatLong(GeoPoint point) {
String address = "Address Not Found";
Geocoder geoCoder = new Geocoder(
getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
point.getLatitudeE6() / 1E6,
point.getLongitudeE6() / 1E6, 1);
if (addresses.size() > 0) {
address =addresses.get(0).getAddressLine(0);
if(address.length()<=0)
address =addresses.get(0).getSubLocality();
}
}
catch (Exception e) {
e.printStackTrace();
}
return address;
}
Here the Google geocode is asynchonous type of function call.
From DOCS:
Accessing the Geocoding service is asynchronous, since the Google Maps
API needs to make a call to an external server. For that reason, you
need to pass a callback method to execute upon completion of the
request. This callback method processes the result(s). Note that the
geocoder may return more than one result.
So you can't get the address like that, instead use the common approach called callback.
Here I have created a sample code to explain the process, which can be altered by yourself.
var geocoder;
function codeLatLng(callback) {
geocoder = new google.maps.Geocoder();
var input = document.getElementById("latlng").value;
var latlngStr = input.split(",", 2);
var lat = parseFloat(latlngStr[0]);
var lng = parseFloat(latlngStr[1]);
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({
'latLng': latlng
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
address = results[1].formatted_address;
callback(address);
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
$('input[type="button"]').on('click', function () {
codeLatLng(function (address) { //function call with a callback
console.log(address); // THE ADDRESS WILL BE OBTAINED
})
});
JSFIDDLE

can create a google map by lat, long in jquery . google maps api

i have lat, long values of a place . how can i create a google map for that lat , long using googl maps api , jquery
is this possible ??
currently iv am getting the lat , long values using
var address = jQuery('#business-address').val();
var city = jQuery('.city').val();
var state = jQuery('.state').val();
var country = jQuery('.country').val();
var address_string = address+","+city+","+state+","+country;
var geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({ 'address': address_string }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
alert(results[0].geometry.location);
}
else {
alert("Geocoding failed: " + status);
}
});
}

Categories