Get Google Maps place name from latitude & longitude - javascript

I am using the Google API (Javascript v3) and need to be able to convert latitude and longitude to a place name (not an address), and visa versa. I have read a lot of articles saying to use the Reverse Geocoding to get this but so far I have only been able to get the formatted_address and not the actual place name.
The code I was using for this is:
function showLocationAddress(e) {
var latlng = { lat: e.latLng.lat(), lng: e.latLng.lng() };
var geocoder = new google.maps.Geocoder;
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
$('#location').empty();
$('#location').val(results[0].formatted_address);
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}
Currently the user can use the autosearch function which within a text field on the map and I can get the place_id, address, and lat and long (as discribed in this link). This is instantiated by calling var autocomplete = new google.maps.places.Autocomplete(input); and the place details are then retrieved using place = autocomplete.getPlace();.
The difficulty I am having is that I also need the same information (place_id, address, and lat and long) to be available when the user clicks on the map, but as I am not using the Autocomplete text field I don't know how to do this.
I thought it would have been something like var place = new google.maps.places.Place(latLng);.

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

Google Maps Geocode - Results relevance

I am using the basic functionality of Google Maps Javascript API
Code sample from google :
https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 8,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
So as you can tell, when we type a street name, even if we have several results, the sample above is just showing one. I already changed that to loop throught all results and it works fine.
My questions are:
The geocoder.geocode results are sorted by any criteria?
If the answer is yes, is it possible to get the results sorted by most relevant / near place of the current user location ? (I will pass the current user location).
Thanks a lot
Closest thing that I know off is using region biasing: https://developers.google.com/maps/documentation/geocoding/intro#RegionCodes
You're using the wrong API for this, try using the Google Places API. This sorts by popularity (preferred).
Or you can use some code to loop through the results and find the distance from the original location. Then you can sort by distance (works, but I think popularity is what you want)

Getting a Return Value From Google Maps Geocoder [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 8 years ago.
I am trying to get a location name according to a lat-long coordinate from the Google maps geocoder. I cannot seem to extract the value from the geocoder callback. Here is my code:
geocoder = new google.maps.Geocoder();
var address = "";
var lat = 54.1234;
var lng = -114.1234;
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng } , function(results,status) {
if (status == google.maps.GeocoderStatus.OK) {
address = results[1].formatted_address; //want to get this address
} else {
address = 'error';
}
});
window.alert(address)
//address is an empty string here, but I want the value from inside the geocoder
//want access to address here to do other operations with it
The documentation for geocoder on the Google Developers site is almost non existant,
and I am having problems trying to find an example that is similar. I am out of my comfort area here, so any help
would be great!
The call is asynchronous, so the value exists inside the callback function:
geocoder.geocode({'latLng': latlng } , function(results,status) {
if (status == google.maps.GeocoderStatus.OK) {
address = results[1].formatted_address; //want to get this address
} else {
address = 'error';
}
window.alert(address);
});
// The code here runs before the callback function

google maps get position

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

Google Places - Get formatted address without user input

I have been sifting through documentation unsuccessfully and need help. I need to access the first value in Google places autocomplete or geocode the lat lng coords I have in Google Places. I am auto populating the field with say "Palo Alto" and need Google Places' first suggestion for an auto complete of that city. I have tried using the Google Geocode feature but the results are different than the Places API and therefore useless to me. Example places outputs Palo Alto, CA and the geocode feature outputs Palo Alto, CA USA. I have tried hacking it together by reverse geocoding the lat lng splitting the string above to only say Palo Alto and populating an input field that is hooked into a Places autocomplete, but I can't get it to trigger. I have a script written to pull the output from the autocomplete results; I just need to trigger it. I have tried using $('myCity').trigger('keypress'); once I have inserted Palo Alto into the input field to no avail. All suggestions on what steps to take next are welcome. I have also looked into the following code, but I want to do it without the map and i get a javascript error when i remove it. "TypeError: a is undefined [Break On This Error] (66 out of range 46)"
var lat = -130;
var lng = 37;
var request = {
location: new google.maps.LatLng(lat, lng);
};
var service = new google.maps.places.PlacesService(map);
service.search(request, function (results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
console.log(results[i])
}
}
});
Thanks for your help.
You need to perform a Text Search.
Go to Places Library and go down to Text Search Requests.
Heres an example:
var map;
var service;
var infowindow;
function initialize() {
var pyrmont = new google.maps.LatLng(-33.8665433,151.1956316);
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: pyrmont,
zoom: 15
});
var request = {
location: pyrmont,
radius: '500',
query: 'restaurant'
};
service = new google.maps.places.PlacesService(map);
service.textSearch(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
createMarker(results[i]);
}
}
}
Note: In your case change the request to this:
var request = {
query: 'Palo Alto'
};

Categories