My problem is with reverse geocoding using Google Maps. I would like to geocode n number(less than 15) of latitude and longitude coordinates so that I can plot a route using the addresses obtained. My problem is when I am using it in a loop it is not giving addresses in the order of lat-lng coordinates passed. The loop is not executing properly. The part of the code that I am having trouble with is:
for(var i=0;i<tlength;i++){
alert(i);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'latLng': latlng[i]},function(results, status) {
alert(i);
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
var add=results[0].formatted_address;
address.push(add);
}
}
});
}
The address array obtained is not in order with the latlng array. Second latlng is getting geocoded first and also the value of i from the 2nd alert box is always 6(in this case tlength=6). It should change from 0 to 5. But it's not happening. Can someone help me with this. Or is their any other way to plot routes using latlong coorinates directly?
Geocoding is asynchronous. The ordering of the callbacks is not guaranteed in in time. One fix would be to use function closure to associate the input index to the callback. Note that the geocoder is subject to a quota and a rate limit. If you don't check for the status returned you won't know when you run into the limit. (the alerts in the code below will get really annoying if you have lots of points in your array...)
var geocoder = new google.maps.Geocoder();
function reverseGeocode(index) {
geocoder.geocode({'latLng': latlng[index]},function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
var add=results[0].formatted_address;
address[index] = add;
} else alert("no results for "+laglng[index]);
} else alert("Geocode failed: "+status);
});
}
for(var i=0;i<tlength;i++){
reversGeocode(i);
}
You need to use like this error in your code :
var latlng = new google.maps.LatLng(51.9000,8.4731);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'latLng': latlng},function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
var add=results[0].formatted_address;
//address.push(add);
alert(results[0].formatted_address);
}
}
});
And for your code you need to pass like this:
for(var i=0;i<tlength;i++){
var latlng = new google.maps.LatLng(latlng[i]);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'latLng': latlng},function(results, status) {
alert(i);
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
// var add=results[0].formatted_address;
address.push(results[0].formatted_address);
}
}
});
}
Related
I already searched in a lot of websites for a solution but no one of them worked.
Since hours I am trying to get the name of the city by using the latitude and longitude values which I will get from a input box to my x, y variables but no example worked.
I also read in the Google maps API but it was not useful.
I already have an API key.
Do you maybe have any solution?
This example I got from the website and tried but without success:
function myFunction() { var x='xxxxx'; var y='xxxxx'; //my coordinates
var geocoder = new google.maps.Geocoder;
var latlng = {lat: parseFloat(x), lng: parseFloat(y)};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
// ...
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}
Look out for Geo location API
Sample Request
http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=false
I have a google map which has a marker on it so people can move it around. When they do I'm attempting to reverse geocode the location into a proper address but I only really want the town/city and the country, I don't want the postcode returned
Is it possible to just get the locality without having to use a regex to remove the postcode - which would prob be difficult!
Thanks in advance
The response didn't only return the address, it also contains the address_components, an array with the specific details of the location, e.g. country, city, street etc. (see https://developers.google.com/maps/documentation/geocoding/#JSON)
fetch the desired components out of this array.
Reverse GeoCoding returns an address_components array containing few objects.
(You can print this object in console to get the feel.)
Extracting required information from this array is very easy.
Now have a look at the code -
function getLatLong(position) {
geocoder = new google.maps.Geocoder();
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
// Reverse Geocoding, Location name from co-ordinates.
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 components=results[0].address_components;
for (var component=0;component<(components.length);component++){
if(components[component].types[0]=="administrative_area_level_1"){
var admin_area=components[component].long_name;
}
if(components[component].types[0]=="country"){
var country=components[component].long_name;
}
if(components[component].types[0]=="postal_code"){
var postal_code=components[component].long_name;
}
}
}
}
}
}
I think you can!
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
for (var i = 0; i < results.length; i++) {
if (results[i].types[0] === "locality") {
var city = results[i].address_components[0].short_name;
var state = results[i].address_components[2].short_name;
alert('Serial=' + i+ ' city=' + city+ ' state=' + state)
};
};
};
};
I am trying to find a set of latitude longitude values and assign it to a variable.
My code looks like this
var k = findLattitudeLongitude("Italy");
console.log(k) // comes undefined
function findLattitudeLongitude(input){
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': input}, function(results, status) {
var location = results[0].geometry.location;
return location;
});
}
but it comes as undefined. What is the best way to achieve the above requirement. Is there any other method?
Actually what you've done is correct.
The problem is the response received from Google geocoder is taking some time.
I've created a fiddle for a better understanding.
it's strange that the function return undefined, what you can do is to call another function, this way work with me fine, you can pass latitude and longitude params like the code below or the whole object
$( document ).ready(function() {
function getlatlan(){
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': "Italy"}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
dosome(results[0].geometry.location.nb,results[0].geometry.location.mb)
return true;
;
}});
}
function dosome(lat,lng){
console.log(lat,lng);
}
getlatlan();
});
I'm working on someone else's code, and I am trying to use Google maps API to convert a street address into latitude and longitude coordinates:
var start_lng;
var end_lat;
var end_lng;
getLat(start);
getLng(start);
function getLat(loc) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': loc}, function postcodesearch(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
var lat = results[0].geometry.location.lat();
alert(lat);
return lat;
//alert(start_lng);
}
else {
alert("Error");
}
});
}
function getLng(loc) {
var geocoder_lng = new google.maps.Geocoder();
geocoder_lng.geocode({'address': loc}, function postcodesearch(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
var lng = results[0].geometry.location.lng();
alert(lng);
return lng;
}
else {
alert("Error");
}
});
}
So far, so good. In the code below, I take that latitude and longitude and perform various calculations with them:
alert("DO REST");
var start_p = new google.maps.LatLng(start_lat, start_lng);
alert(start_p);
var end_p = new google.maps.LatLng(end_lat, end_lng);
The problem is that since the call that gets the latitude and longitude is asynchronous, the code below doesn't wait to get the values before it tries to use them. They show up as undefined. I tried putting the second half of the code in its own function and calling that at the end of the longitude request, but that only worked if the longitude call happened to finish first. I also tried $.ajax({ async:false}) but that didn't do anything. This is my first time dealing with AJAX, so I'm really not sure which way to go.
For the "handler" code, use a callback instead:
function getLatLng(loc, callback) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': loc}, function postcodesearch(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
var lat = results[0].geometry.location.lat();
var lng = results[0].geometry.location.lng();
callback(lat, lng);
}
}
}
getLatLng(function(lat, lng) {
alert("DO REST");
var start_p = new google.maps.LatLng(lat, lng);
});
If you need to make two calls to the geocoder, then you can always nest those calls, and put the callback after both are complete. Something like:
function getLatLng(locStart, locEnd, callback) {
geocoder.geocode({ }, function(results1) {
geocoder.geocode({ }, function(results2) {
callback(results1.lat, results1.lng, results2.lat, results2.lng);
});
});
}
getLatLng(loc1, loc2, function(lat1, lng1, lat2, lng2) {
});
use global flag variables
for example:
var flag_lat = var flag_lnt = 0;
then add in your postcodesearch functions flag_lat=1; and flag_lng=1; respectively
and in the end of each postcodesearch function check
if (flag_lat && flag_lng)
{
do_the_things_function();
flag_lat = flag_lng = 0; //reset the flags
}
I'm using Google maps api, and I got a problem when I'm trying to get markers position.
I got two text fields as an address input, and i show the results with markers.
When I want to get the markers position(by getPosition() function), for using new google.maps.LatLngBounds(), the markers position is correct on the map, but the getPosition() function, gives me a wrong answer, only on the second time I search for the address the getPosition, is updated for the first address search.
It's like it has a dealy and when I'm using getPosition(), the position is not updated yet.
Anyone have any idea why?
Thanx
This is part of my code.
If I'll use JSON request for getting the address location, will it work better?
function GetAddress(add , map , pointtype) {
var country = 'france';
var address = add + ', ' + country;
geocoder = new google.maps.Geocoder();
if(pointtype == 0){
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
origmarker.setPosition(results[0].geometry.location) ;
origmarker.setTitle(add);
}
});
}
else{
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
desmarker.setPosition(results[0].geometry.location) ;
desmarker.setTitle(add);
}
});
}
}
var bounds = new google.maps.LatLngBounds() ;
bounds.extend(origmarker.getPosition());
bounds.extend(desmarker.getPosition());
map.fitBounds(bounds);
Sounds like you are using the geocoder to place the markers on the map. The geocoder is asynchronous, you can't use the results until the callback routine runs. Sounds like you are trying to use the position of the marker before the callback runs (so you get the value from the last call).