Getting Latitude and Longitude from Google Places Autocomplete API - google-maps

Im using the Google Places Autocomplete API, to have an input in which users type a city and get suggestions for which place they are searching for.
I need to get not only the name of the place but the Latitude and Longitud of the place for then centering a google map there.
The problem is that Google Places Autocomplete API just returns description of the place but not the coordinates, at least with what i tried.
Anybody knows if there is a way to get the Latitud & Longitud in the same request?
Many thanks to any help :')

All the information you are looking for can be found inside the Place Result. This is what your code would look like:
var input = document.getElementById("address");
var autocomplete = new google.maps.places.Autocomplete(input, {types: ["geocode"]});
autocomplete.addListener("place_changed", function() {
var placeResult = autocomplete.getPlace();
var name = placeResult.name;
// The selected place's position
var location = placeResult.geometry.location;
// The preferred viewport when displaying this Place on a map.
// This property will be null if the preferred viewport for the Place is not known.
var viewport = placeResult.geometry.viewport;
// This is assuming your google map is saved in a variable called myMap
if (viewport) {
myMap.fitBounds(viewport)
}
else if (location) {
myMap.setCenter(location)
}
});
I recently created a jQuery plugin that makes interacting with Google Maps Autocomplete a breeze. This would be the code to center a map every time a place was selected:
$("#address").geocomplete({
map: myMap
});
The plugin will also allow you to autofill an address form, adds custom styling, provides callbacks and fixes an annoying scrolling issue.

Related

Getting my current position from my phone with script in Google spreadsheet

Is there a way to get my current position (latitudes and longitudes, preferably in decimal form) from my phone's GPS data with a Google Apps Script?
Also, is it possible to turn GPS on and off or at least detect if it's on or off?
Here's what I try to do:
I go to places with my electric moped, and at every place I enter some data in a spreadsheet, such as date, distance since last position, which battery I'm using and more. One of the columns is my position. I currently enter it manually, but some positions are very common (for instance ”Work” and ”Home”) and it would be convenient if a script entered my position for me on edit.
I do that already, but it's very primitive at the moment. The only thing it does now, is check if it's a working day, and in that case, if my last position was ”Home”, it will enter ”Work”, and ”Home” if my last position was ”Work”. That takes care of the most common situations, but there are a few more places I go to often, so I figured that if I can get my current GPS coordinates from my phone, I could use them for figuring out if I'm at work, at home, or at one of the grocery stores I visit often or whatever.
I have searched for the answer, but all I can find is how to convert addresses to coordinates and the other way around, which obviously is not what I'm looking for at all.
I think we can try Geolocation API
Something like this (be mindful about handling user consent):
navigator.geolocation.getCurrentPosition(function(location) {
console.log(location.coords.latitude);
console.log(location.coords.longitude);
console.log(location.coords.accuracy);
});
https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API
Credits : Get GPS location from the web browser
Google Apps Script doesn't include a direct way the GPS data but this is possible by creating a Web App and using the Geolocation API.
Example:
I adapted the code frond on the above link to
Use it in a Google Apps Script web application
Log the latitude and longitud into a spreadsheet
Code.gs
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('index');
}
function saveCoordinates(latitude,longitude){
const sheet = SpreadsheetApp.getActiveSheet();
const rowContents = [latitude,longitude];
sheet.appendRow(rowContents);
}
index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<button id = "find-me">Show my location</button><br/>
<p id = "status"></p>
<a id = "map-link" target="_blank"></a>
<script>
function geoFindMe() {
const status = document.querySelector('#status');
const mapLink = document.querySelector('#map-link');
mapLink.href = '';
mapLink.textContent = '';
function success(position) {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
google.script.run.saveCoordinates(latitude,longitude);
status.textContent = '';
mapLink.href = 'https://www.openstreetmap.org/#map=18/' + `${latitude}\/${longitude}`;
mapLink.textContent = `Latitude: ${latitude} °, Longitude: ${longitude} °`;
}
function error() {
status.textContent = 'Unable to retrieve your location';
}
if(!navigator.geolocation) {
status.textContent = 'Geolocation is not supported by your browser';
} else {
status.textContent = 'Locating…';
navigator.geolocation.getCurrentPosition(success, error);
}
}
document.querySelector('#find-me').addEventListener('click', geoFindMe);
</script>
</body>
</html>
To use the above in your phone, you could add the link to the web application into your spreadsheet, so it can be openened on the phone web browser. In order to make this work you need to have an Internet connection enabled.

Working with php/mysql display information on google maps

I have a MySQL address database which contains all the necessary information to look up the address on google maps. Each row with data contains an extra field naming LATLNG. Which contains the Lat and Lng in the preferred format of google maps. ####, ####. I have already created a viewing page with a ‘show’ button to display the content on a separated html page in Google maps with the address above it.
The problem is that I could find all kinds of tutorials (also from google themselves) with the vast possibility’s that google maps provide. The feature I would like to use however isn’t found in a tutorial. And whatever I do, I seem to get stuck with the result of it.
Example (own database):
After each address field there is a button with the next caption:
echo '<td>Show</td>';
Example (google maps) what opens after pressing the SHOW button:
<script>
function myMap() {
var Lelystad = new google.maps.LatLng(LAT LNG INFORMATION);
var mapCanvas = document.getElementById("map");
var mapOptions = {center: TOWN NAME, zoom: 15};
var map = new google.maps.Map(mapCanvas, mapOptions);
var marker = new google.maps.Marker({position:TOWN NAME});
marker.setMap(map);
var infowindow = new google.maps.InfoWindow({
content: "DISPLAY CONTENT OF ADDRESS ABOVE MARKER"
});
infowindow.open(map,marker);
}
</script>
What I want is that after pressing the ‘show’ button the latlng from that given address is being picked up by google maps and show it.
Hopefully someonw can help me, if some of the information is not clear enough don't hesitate to ask me.
I am not sure you want to use the JavaScript. There is a very simple API giving you the latitude and longitude through a URL:
http://maps.googleapis.com/maps/api/geocode/json?address=eiffel%20tower,paris
where "address" is the address you are looking for. You must first register to obtain a key and you are limited to 2500 requests per day (but you can store the results in the database).
See full documentation here: https://developers.google.com/maps/documentation/geocoding/intro?hl=fr

Google Maps API get longitude and latitude clicking on the map

I'm trying to build a really useful web service and want to simplify the place choose using google maps. Is there any possibility to get longitude and latitude and write it down to input tags just by clicking on the map?
Here's how i would do this:
var map = ...;
google.maps.event.addListener(map, 'click', function (event) {
$('input.latitude').val(event.latLng.lat());
$('input.longitude').val(event.latLng.lng());
});

GMaps API: Search Map via Lat/LonCoordinates and Addresses

I've been using the Geocoder service in the Google Maps API to power a search box on my map. I wish to allow users to search freely by address, city and coordinates and perhaps anything else that is supported. Until recently if I passed latitude/longitude coordinates to the geocoder it would simply return me a result of those specific coordinates but lately it has changed to do a reverse lookup and provide me the nearest address to the coordinates. I actually want the location directly at the coordinates as that is what is most relevant.
Any ideas how to either parse out the various input forms of coordinates from the search box or get the geocoder to revert to its earlier behaviour?
I'm not sure why it would have changed to showing reverse geocoding, without seeing the code. However, I would suggest using the Autocomplete feature of the Places API Library instead.
Couldn't you just use a regex to check if the input entered is a lat/lng pair? And then if it is parse that pair and navigate to the coordinates directly. Something like:
var latLngRegex = /^(\-?\d+(\.\d+)?),\s*(\-?\d+(\.\d+)?)$/; //Regex for checking that it is a latlng pair that has been entered
var address = document.getElementById("txt_googlesearch").value;
if (address=='' || address=='Search') {
return;
}
if (latLngRegex.test(address)) //Run the regex against the entered value
{
var coords = address.split(","); //Split the address into 2 decimal values
var mapPoint = new GLatLng(parseInt(coords[0]), parseInt(coords[1])); //Create a gLatLng from the split values
map.setCenter(mapPoint); //Move the map to the entered location
return;
}
//Call Geocoder as before

Embedded google maps map in directions page

I want to have my directions page having the same functionality as this page i.e. the Google Map object is updated from the form on the right. How can I have this in my pages? I'm using Django BTW, but I don't think this will matter much...implementation should be universal for something like this.
I've done this within a Drupal Site. The code API is pretty straight forward. You can generate the initial interactive map using your longitude and latitide as the center point.
function initialize() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(37.4419, -122.1419), 13);
}
}
Then you need to have your directions form make a call to the Google Geocoder. This will turn the address entered into longitude and lattitude - although you maybe able to bypass this step.
Then, use the newly acquired Long & Lat to generate a directions request (Google API, again).
// Create a directions object and register a map and DIV to hold the
// resulting computed directions
var map;
var directionsPanel;
var directions;
function initialize() {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(42.351505,-71.094455), 15);
directionsPanel = document.getElementById("route");
directions = new GDirections(map, directionsPanel);
directions.load("from: 500 Memorial Drive, Cambridge, MA to: 4 Yawkey Way, Boston, MA 02215 (Fenway Park)");
}
All of the Javascript can go directly in your HTML. I suggest you take some time to study http://code.google.com/apis/ajax/playground/