google maps get position - javascript

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).

Related

How to find city name with latitude and longitude in JavaScript?

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

Javascript change value of global variable

var longitude=1;
var latitude=1;
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': Position}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
alert(results[0].geometry.location.lat());
alert(results[0].geometry.location.lng());
latitude = results[0].geometry.location.lat();
longitude = results[0].geometry.location.lng();
//alert("location : " + results[0].geometry.location.lat() + " " +results[0].geometry.location.lng());
} else {
alert("Something got wrong " + status);
}
});
I am trying to change the values of global variables latitude and longitude but not able to. I have looked up the way to assign values to global variables inside a function and I think I am doing that part right. But clearly there is something that I am missing. Please help.
The function(results, status){ ... } bit is an asynchronous callback
The issue you're likely running into is that you're trying to access the longitude and latitude values before they're actually set
To confirm this, modify your callback to the following
// where you have these two lines
latitude = results[0].geometry.location.lat();
longitude = results[0].geometry.location.lng();
// add this line after
console.log(latitude, longitude);
You should see them just fine. Once you have that bit working, you could skip them altogether and do something like this
function doSomething(lat, lng) {
console.log(lat, lng);
}
geocoder.geocode( { 'address': Position}, function(results, status) {
// ...
var loc = results[0].geometry.location,
lat = loc.lat(),
lng = loc.lng();
doSomething(lat, lng);
// ...
});
This way you can skip having latitude and longitude in the outer scope, too. Pretty handy!
I recommend you attach those two variable to the global window object.
Like: window. latitude and window.longitude
And the function trying to change the value is an async callback function, there might be local variable with the same name defined in that scope.
Attaching it to window should get you around that possibility.
Try this code:
var longitude=1;
var latitude=1;
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': Position}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
latitude = results[0].geometry.location.lat();
longitude = results[0].geometry.location.lng();
alert(latitude + ', ' + longitude) // show the value of the globals
} else {
alert("Something got wrong " + status);
}
});
If that works correctly, then the answer is probably that the globals are being correctly set, but they simply haven't been set by the time other code attempts to use them.
If this occurs, it means that whatever code relies on the lat/long needs to wait until the geocode callback has finished and received data.

Reverse geocoder not working properly when used in a loop

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

Getting latitude & longitude values of different places to a value

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

How to return address types from google maps geocode?

I am currently using the google maps api to geocode locations on the map and return the address of the street.
I currently return the address with the following code:
function codeLatLng(markerPos) {
geocoder.geocode({'latLng': markerPos}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
//Set markerAddress variable
var markerAddress = results[0].formatted_address;
alert(markerAddress);
...
But what if I don't want to return the formatted address but a more detailed version using Address Component Types, how can I return certain address values like: http://code.google.com/apis/maps/documentation/geocoding/#Types
Help appreciated.
May I ask, why are you checking for results[1] and then using results[0] (or is it just a typo I should ignore)?
As long as status is OK, there will be at least one result.
Otherwise, status would be ZERO_RESULTS.
Anyway, you can use something like this:
function codeLatLng(markerPos) {
geocoder.geocode({'latLng': markerPos}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var markerAddress = results[0].address_components[0].long_name
+ ' (type: ' + results[0].address_components[0].types[0] + ')';
alert(markerAddress);
You can play a lot with the whole address_components array, have fun! :)
For even more fun, have a look at the (source code of the) Google Maps API v3 Geocoder Tool at http://gmaps-samples-v3.googlecode.com/svn/trunk/geocoder/v3-geocoder-tool.html
long_name is the full text description or name of the address component as returned by the Geocoder.
function codeLatLng(markerPos) {
geocoder.geocode({'latLng': markerPos}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
//Set markerAddress variable
var markerAddress = results[0].long_name;
alert(markerAddress);
...

Categories