Why did the latitude results object change from the google maps api? - javascript

I am hitting the google maps api while passing in a city like so:
this.geoCode = function(city) {
var dfd = $q.defer();
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': city},
function (results, status) {
console.log('map response: ', results);
cityObj.address = results[0].formatted_address;
getWeather(results[0].geometry.bounds.R.R, results[0].geometry.bounds.j.j)
.then(function(response) {
cityObj = response;
dfd.resolve(cityObj);
});
});
return dfd.promise;
};
Just 2 weeks ago I was accessing the latitude/longitude from the results object by:
getWeather(results[0].geometry.bounds.R.R, results[0].geometry.bounds.j.j)
Now the results object looks like this:
getWeather(results[0].geometry.bounds.H.H, results[0].geometry.bounds.j.j)
as you can see, the latitude went from being accessed on the R.R object to being accessed on the H.H object. I don't know if this is something googlemaps frequently does. If it is, how could use the code to continually parse through the data to get the latitude/longitude without continually changing the object letters? Any feedback would be greatly appreciated. Thanks

That is due to it being minified, the property names aren't always named the same and aren't meant to be accessed directly.
geometry.bounds is a LatLngBounds instance. As such you use the methods like getCenter() to get a LatLng object which you can then get the latitude and longitude values
var center = results[0].geometry.bounds.getCenter();
var lat = center.lat();
var lng = center.lng();
Or you can also use geometry.location as it is already a usable LatLng instance, it all depends on which coordinates you are needing to retrieve.

Related

How can i get latitude and longitude coordinates from JSON Google Maps

I know what i can get JSON LatLon (and other) data indicate my address in the URL
app.factory('myCoordinates', function myCoordinates($q, $http) {
var deferred = $q.defer();
$http.get('http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false&region=$region')
.success(function(coordinates) {
var myCoordinates = {};
myCoordinates.lat = coordinates.results[0].geometry.location.lat;
myCoordinates.lng = coordinates.results[0].geometry.location.lng;
myCoordinates.zoom = 14;
deferred.resolve(myCoordinates);
})
return deferred.promise;
});
http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false&region=$region
But how can i get latitude and longitude coordinates of my current location without input my address in URL (automatically) ?
How about using html5 navigator.geolocation.getCurrentPosition to get the latitude and longitude?
Example:
navigator.geolocation.getCurrentPosition(function(pos){
console.log(pos)
});

Get Google Maps place name from latitude & longitude

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

Can't get Googlemaps Geocoder to return LatLng with callback

Can someone look at my code and tell me what I'm doing wrong? I understand that the Googlemaps geocoder is an async function so there needs to be a callback to handle the results. So I'm following the example here but I still can't get it to work:
How do I return a variable from Google Maps JavaScript geocoder callback?
I want to give my codeAddress function an actual address and a callback function. If the results array has something I send the lat and lng to the callback function.
codeAddress = function(address, callback) {
var gpsPosition = {};
if (geocoder) {
geocoder.geocode({'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
console.log("got results!");
var lat = results[0].geometry.location['B'];
var lng = results[0].geometry.location['k'];
callback(lat, lng);
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
};
This is the callback function. Basically it takes the lat and lng from the codeAddress function and puts the lat and lng into a hash and returns it. The idea is to then store the hash into a variable called location and reference location when I'm creating a new map marker.
createGPSPosition = function(lat, lng){
console.log("createGPSPosition called with lat and lng:");
console.log(lat);
console.log(lng);
var gpsPosition = {};
gpsPosition.B = lat;
gpsPosition.k = lng;
console.log("gpsPosition:");
console.log(gpsPosition);
return gpsPosition;
};
When I run this code console.log(gpsPosition); actually logs the final hash object. But I still don't see the object getting returned... so when I do:
var stuff = codeAddress("1600 Amphitheatre Pkwy, Mountain View, CA 94043", createGPSPosition)
stuff still turns up as undefined. What's going on here?
This problem is that you're expecting asynchronous code to work in a synchronous way. stuff is defined before codeAddress finishes searching. The simplest solution is to provide a different callback, define stuff within that and use it there. This should work fine:
codeAddress("1600 Amphitheatre Pkwy, Mountain View, CA 94043", function(lat, lng){
var stuff = createGPSPosition(lat, lng);
console.log(stuff); // => your gpsPosition object
});
An alternative would be to learn Promises.

Convert latitude, longitude in to address as a string

Please help me resolve this problem.
I want to get address from latitude, longitude in Google Maps.
Here is my functions:
function codeLatLng() {
var geocoder = new google.maps.Geocoder();
var lati = document.getElementById("latitude_value").value;
var lngi = document.getElementById("longitude_value").value;
var latlng = new google.maps.LatLng(lati, lngi);
var infowindow = new google.maps.InfoWindow();
var ngo;
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
map.setZoom(11);
marker = new google.maps.Marker({
position: latlng,
map: map
});
ngo = results[1].formatted_address;
infowindow.setContent(results[1].formatted_address);
infowindow.open(map, marker);
}
} else {
alert("Geocoder failed due to: " + status);
}
});
return ngo;
}
When this function is executed. The address is displayed in Maps.
However, this is not what I need. I just want to assign this address to variable 'ngo' as a string.
This function return 'ngo' which is displayed in the text field as 'undefinded'.
I need some help to solved this problem.
Thanks.
I just want to assign this address to variable 'ngo' as a string.
That's the problem right there. You can't do that. JavaScript just doesn't work that way. The geocoder call is asynchronous. It returns before the data is received from the server. The data isn't ready until the geocoder callback function is called.
What you need to do instead is to use that ngo data in the callback function itself, or call another function and pass it the data, and use the data there.
For example, where you have this line:
ngo = results[1].formatted_address;
you can replace it with:
useNGO( results[1].formatted_address );
where useNGO is a function you've defined (anywhere) like this:
function useNGO( ngo ) {
// Do stuff with ngo here
}
I believe your problem is that using the var keyword when declaring var ngo makes ngo a local variable, so it doesn't exist outside of codeLatLng(). Try deleting var ngo, placing ngo = ""; somewhere outside of any function declarations (like right before function codeLatLng() {), and let me know if that works :)

Geoencode Address to GPS Coordinates

I'm looking to geoencode an address and convert it to GPS Coordinates. Basically,
var address;
// Google/Yahoo/whatever program to convert address to GPS coordinates
var output=xx.xxxxxxx,xx.xxxxxxx
I've researched Google and Yahoo APIs, but can't seem to get their codes to work in my Google Gadget. Any suggestions?
Thanks in advance!
Here's what I did for my address-to-gps-coords needs:
function get_coords(address)
{
var gc = new google.maps.Geocoder(),
opts = { 'address' : address };
gc.geocode(opts, function (results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
var loc = results[0].geometry.location,
lat = loc.$a,
long = loc.ab;
// Success. Do stuff here.
}
else
{
// Ruh roh. Output error stuff here
}
});
}
Then you call it like get_coords('1600 Pennsylvania Avenue NW Washington, DC 20500') and it'll return the latitude and longitude.
You'll need to supply your own Google Maps API key to make it work, of course.
Hope this helps!
I did this and worked perfect:
<script type="text/javascript">
var dir1 = "5th ave, new york";
var google_url = "http://maps.googleapis.com/maps/api/geocode/json?address=";
var sensor = "&sensor=false";
var resultado;
function myFunction(){
$.getJSON(
google_url+dir1+sensor,
function(result){
$( "body" ).append( "Latitude: " + JSON.stringify(result.results[0].geometry.bounds.northeast.lat) )
$( "body" ).append( "Longitude: " + JSON.stringify(result.results[0].geometry.bounds.northeast.lng) )
});
}
I help to maintain one API called LiveAddress which does this. Much easier to use than Google/Yahoo's APIs, and without the restrictive Terms of Service which prohibit requests en masse, storing the results, or using the data without showing a map or by automation.
Here's a complete example, using this sample wrapper function:
LiveAddress.init(123456789); // your API key here
LiveAddress.geocode("address goes here", function(geo) {
// You can also pass in an array of addresses,
// the ID of a DOM element containing the address,
// or an array of IDs
console.log(geo);
});
Individual coordinates are found in geo.lat and geo.lon, with the combined string "lat, lon" format in geo.coords. You can also obtain the precision of the data with geo.precision.

Categories