Geoencode Address to GPS Coordinates - javascript

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.

Related

How to access google maps API response data

First time trying to hack together some Javascript here so any resources that will help me understand my problem case is appreciated.
I'm trying to extract the lat and long from the following request to use in another request:
var placeSearch, autocomplete;
var x = document.getElementById("location");
function initAutocomplete() {
// Create the autocomplete object, restricting the search predictions to
// geographical location types.
autocomplete = new google.maps.places.Autocomplete(
document.getElementById('autocomplete'), { types: ['geocode'] });
// Avoid paying for data that you don't need by restricting the set of
// place fields that are returned to just the address components.
autocomplete.setFields(['geometry']);
}
function showPosition() {
x.innerHTML = "Latitude: " + autocomplete.result.geometry.lat +
"<br>Longitude: " + autocomplete.result.geometry.lng;
}
/*
"result" : {
"geometry" : {
"location" : {
"lat" : 51.46588129999999,
"lng" : -0.1413263
}
}
*/
// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var geolocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var circle = new google.maps.Circle(
{ center: geolocation, radius: position.coords.accuracy });
autocomplete.setBounds(circle.getBounds());
});
}
}
When a user selects the autocompleted location the google api makes a request to:
https://maps.googleapis.com/maps/api/place/js/PlaceService.GetPlaceDetails on the selected location. I can see this returns my desired data here:
Obviously autocomplete.result.geometry.lat returns a location_search.js:18 Uncaught TypeError: Cannot read property 'geometry' of undefined error so I'm missing some knowledge here.
Thank you for your help.
I've implemented something very similar to your needs in my project recently. It's quite easy but it took me a while to realise how to do it.
Basically, you can simply use the .getPlace() method on the Autocomplete object and go from there. Here's how I got the latitude and longitude:
let locationInfo = autocomplete.getPlace().geometry.location;
let latitude = locationInfo.lat();
let longitude = locationInfo.lng();
In your specific case you should change your showPositions function to
function showPosition() {
x.innerHTML = "Latitude: " + autocomplete.getPlace().geometry.location.lat +
"<br>Longitude: " + autocomplete.getPlace().geometry.location.lng;
}
Does this do the trick?

Determine whether a random coordinate (latitude, longitude) is on the particular route

I'm developing a cross platform application with IONIC/CORDOVA. How can I determine whether a random coordinate (latitude, longitude) with 50 meters radius is on the particular route?
Suppose I have a route defined from one area to another area. I need to find out the users of my application who are on that particular route.
What is the best way to implement this task? Google MAPS API or OpenStreetMap?
Regards
Ashikur Rahman
I would use Google Maps Geocoding API.
Example:
var xhr = new XMLHttpRequest(),
route = "E261", // route name
latlng = "52.3547673,16.8840211"; // lat and lng
xhr.open("GET", "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + latlng, true);
xhr.addEventListener("load", function() {
var response = JSON.parse(xhr.response).results;
response.forEach(function(result) {
if (result.types.indexOf("route") !== -1 && result.formatted_address.indexOf(route) !== -1)
console.log("route found");
});
});
xhr.addEventListener("error", function() {
// handle error
});
xhr.send();

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

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.

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

Google maps custom markers issues

I am trying to visualize some fusion tables data on google maps.
I have a number of records with addresses grouped by area number.
Basically what I would want to happen is the following:
I pull data from ft
For each record, I geocode the address
and assign a custom marker according to the area number
I visualize all the different records grouped by different markers
Here is what I've done so far:
This is the query to ft:
var query = "SELECT 'Full Address' , Territory FROM " + tableid;
query = encodeURIComponent(query);
var gvizQuery = new google.visualization.Query(
'http://www.google.com/fusiontables/gvizdata?tq=' + query);
Now I want to elaborate the query data
gvizQuery.send(function(response) {
var numRows = response.getDataTable().getNumberOfRows();
// For each row in the table, create a marker
for (var i = 0; i < numRows; i++) {
var stringaddress = response.getDataTable().getValue(i, 0);
var territory = response.getDataTable().getValue(i,1);
**latlng**(stringaddress,
function(data){
console.log(data);
**createMarker**(data,territory,stringaddress);//callback
});
}
});
Here is the latlng function: that returns a google maps point from the string address
function latlng(address,callback){
var latlng;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
"address": address
}, function(results,status) {
if ( status == google.maps.GeocoderStatus.OK ) {
latlng= new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng());
callback(latlng);
}
});
}
And finally here is the create marker function
var createMarker = function(coordinate, territory,address) {
console.log("now drawing marker for " + coordinate + "found in territory number " + territory);
var markerpath="images/icon"+territory+".png";
var marker = new google.maps.Marker({
map: map,
position: coordinate,
icon: new google.maps.MarkerImage(markerpath)
});
google.maps.event.addListener(marker, 'click', function(event) {
infoWindow.setPosition(coordinate);
infoWindow.setContent('Address: ' + address + '<br>Territory = ' + territory);
infoWindow.open(map);
});
};
The issue I am facing is that ,although I should be calling the createmarker function for each record of my ft, it is actually only being called a couple of times (out of 250) and only one territory is being represented (number 7).
What am I mising?
Thank you for your help!
The geocoder is subject to a rate limit and a quota, after about 10 geocode operations you will see the status returned of OVER_QUERY_LIMIT (which your code silently ignores). To see the issue, log the status returned:
function latlng(address,callback){
var latlng;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
"address": address
}, function(results,status) {
if ( status == google.maps.GeocoderStatus.OK ) {
latlng= new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng());
callback(latlng);
} else {
console.log("geocode failed: "+status);
}
});
}
(or you could add an alert, which would be really annoying for 200 markers)
You need to handle the OVERY_QUERY_LIMIT appropriately (throttle your requests), but that will probably make your map load too slow.
Best option: geocode the addresses offline and store the coordinates in the FusionTable, return them in your query and use those to display the markers.

Categories