How can I get google maps location names? - google-maps

I'm building a site in which it is required to get all google maps locations, from countries names to the smallest village. Is this anywhere in the api? Because it is nowhere to be found.

You need to parse the response to get that data out, so for example if you want to get the country and results is the result object you get by calling the reverse Gecoding:
https://developers.google.com/maps/documentation/javascript/geocoding#ReverseGeocoding
Then the function for getting the country would be:
function getCountry(results) {
var geocoderAddressComponent,addressComponentTypes,address;
for (var i in results) {
geocoderAddressComponent = results[i].address_components;
for (var j in geocoderAddressComponent) {
address = geocoderAddressComponent[j];
addressComponentTypes = geocoderAddressComponent[j].types;
for (var k in addressComponentTypes) {
if (addressComponentTypes[k] == 'country') {
return address;
}
}
}
}
return 'Unknown';
}

If you need the "name" associated with a place on a Google Maps API v3 map based on its geographic coordinates (latitude and longitude), use the reverse geocoder, it returns many levels of information for that location.
Example from the documentation
Note, that except for the fact that it won't necessarily correlate with the Google Maps API v3 tiles, geonames.org might have the information you need or a less restrictive service to get it.

Related

API to convert lat lon to NYC neighborhood

Is there a hosted API that converts a latitude and longitude into a Manahttan neighborhood?
I know that Zillow has a shapefile but I'd much rather just use an API.
I've looked a few questions. It looks like NYC open data also has neighborhood information.
The closest I've come to finding an API that takes lat lon is the times Districts API but it seems to be deprecated as it's not on their list of API's and the links redirect to those lists.
Is there a publicly available API? Or do I need to create a heroku app with a zillow shapefile and create my own?
Google maps only returns manhattan in its geocoding response, not a specific neighborhood in Manhattan
You can use MapBox API for reverse geocoding and parse the JSON data obtained to extract the Neighborhood name.
I made a small example that you can inspire from.
Code:
//You can get your access_token if needed from mapbox.com
var access_token = '?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw';
var urlInit = 'https://api.mapbox.com/geocoding/v5/';
var mode = 'mapbox.places/';
var type = '&types=neighborhood';
$('#go').click(function() {
$('#result').html('');
lonlatInput = $('#lonlat').val();
lonlatInput = lonlatInput.split(',');
lonlat = lonlatInput[0].trim() + '%2C' + lonlatInput[1].trim() + '.json';
getNeighborhood(lonlat);
});
function getNeighborhood(lonlat) {
var url = urlInit + mode + lonlat + access_token + type;
$.ajax({
type: 'GET',
url: url,
success: function(rgeo) {
var result = rgeo;
var neighborhood = rgeo.features[0].text;
$('#result').html(neighborhood);
},
error: function(rgeo) {
console.log(rgeo);
}
});
}
#result {
padding: 10px;
font-size: 2em;
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="-73.945462,40.830182" id="lonlat" />
<button id="go">Geocode</button>
<div id="result"></div>
See this example in JsFiddle
There are a couple of solutions to your objective such as CartoDB integrations, Bing Location API, geopy, geocoder, SmartyStreets API and others.
Let us explore this using CartoDB:
Create a file with longitude and latitude coordinates in NYC.
Use an NYC neighborhoods geometry file from Zillow
Upload the files to Cartodb and geoencode the longitude and latitude coordinates as a geometry object in your longitude and latitude coordinate file.
Run the following SQL query from within the file:
SELECT a.*,
b.neighborhood
FROM inputFileName
as a,
nyc_pediacities_neighborhoods_v3_polygon as b
WHERE ST_Within(a.the_geom,b.the_geom)
We are creating two objects, inputFile as a and the shapefile as b, then match the geometries against one another with the WHERE clause.
We are creating a new column with rows denoting the NYC neighborhood of the longitude and latitude of the same row.
Simply export the file in a desirable format and enjoy the information.
One can easily automate the process using one of their integrations. This will closely act as an ideal API. See this
The python package geopy also deserves attention. Check this
One can achieve the same result using the Bing Location API. See API
Another feasible solution is to construct your own API from the open data.
Check geocoder and SmartyStreets

Google Apps Script - How to get driving distance from Maps for two points in spreadsheet

Good evening,
I have a spreadsheet where I record my daily driving mileage when working. The column headings are: Date, Point A, Point B, Point C, Point D, Point E, Point F, Point G, and Trip Mileage.
Currently, I manually use Google Maps to determine driving distance between points. What I'd like to see happen instead is for a script to pull the points data from my spreadsheet, determine distance between the points and total distance of each trip (i.e. row), and insert the total in the last column.
I believe I have this essentially all set up except I can't figure out how to get the distance data from Google Maps. From reading similar question, I sense someone might tell me to refer to the Maps Distance Matrix API. I've referred to this. I'm a beginner programmer, but it appears to me to be oriented toward apps, not Google docs. Is this the case? Or can it be made to serve my project?
Thank you in advance for all of your wonderful advice, comments, suggestions, and encouragement!!!
BTW, here is my code currently:
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var mileageLogSheet = ss.getSheetByName("Mileage Log");
var dataRange = mileageLogSheet.getDataRange(); //Returns a Range corresponding to the dimensions in which data is present.
var numRows = dataRange.getNumRows();
var numCol = dataRange.getNumColumns(); //numCol = 9.
//Returns the range with the top left cell at the given coordinates (row, column) with the given number of rows and columns.
var rangeToCompute = mileageLogSheet.getRange(10, 2, numRows-9, numCol-1);
var address1,
address2;
for(var rowCoord = 1; rowCoord < numRows-9; rowCoord++){
for(var colCoord = 1; colCoord < 8; colCoord++){
if(rangeToCompute.getCell(rowCoord, colCoord).getValue() != ""){
address1 = rangeToCompute.getCell(rowCoord, colCoord).getValue();
address2 = rangeToCompute.getCell(rowCoord, colCoord+1).getValue();
var directions = Maps.newDirectionFinder()
.setOrigin(address1)
.setDestination(address2)
.setMode(Maps.DirectionFinder.Mode.DRIVING)
.getDirections();
//Nope, this doesn't work!:
var distanceValue = directions.routes[0].legs[0].distance.value;
var totalTripDistance;
}
}
}
}
You can take use of the Google Maps WEB API's Direction API. Which give you a detail result on direction from point A to point B, which include the distance information you want.
To get started, you need an API KEY for using the Google Maps Direction API. Go to console.developers.google.com to create an account, create a project, enable the Directions API in your project and then create a credential (API KEY). You should able to create it as server API key and give it the address 0.0.0.0/0, which means all computer on earth, as long as you keep this project to yourself. For more information on creating API KEYS, you can take a look at this section.
Then in the spreadsheets, you need to first create the request URL by CONCAT your key, origin and destination. Here is how I did it:
=CONCAT(CONCAT(CONCAT(CONCAT(CONCAT("https://maps.googleapis.com/maps/api/directions/json?origin=",SUBSTITUTE(B2," ","+")),"&destination="),SUBSTITUTE(C2," ","+")),"&key="),$A$2)
*Note that you need to SUBSTITUTE spaces " " to pluses "+"
Then under the Tools > Script editor..., create an empty script and replace everything with the following code, and save:
function getDistance(url) {
var response = UrlFetchApp.fetch(url);
var json = response.getContentText();
var data = JSON.parse(json);
var distance = data.routes[0].legs[0].distance.text;
return distance;
}
This is a customized function that parse the Google Maps Direction API JSON result and return the distance information. The JSON usually contains multiple routes and under the first route- routes[0], exist multiple legs and in the first leg- legs[0], exist a distance, which include a text and value field, which are a human readable field, and a integer number that represent the distance in meter.
return to the spreadsheets and you can call =getDistance(CellWithURL) to get the distance between two places.
I created an example here, hope it helps.
**ps. somehow it works without the API KEY too.. but you should apply for one for otherwise you violate the ToS.

Google Places API - Counting the total number of places in a given radius around a lat / long?

Slightly unusual request, but just wondered if anyone knows of a way to calculate the total number of places in the Google Places places database within a given radius (or polygon) around a lat / long?
Many thanks in advance!
There is no way to query the Places API for the total number of places that fall within a given radius in the Google database. When you query the Places API, the maximum number of results that will be returned is 20 (twenty) as described in this question/answers: What is the proper way to use the radius parameter in the Google Places API?.
Maybe I'm misreading the question, but here goes. Check out the Places API example; its search results is an array, so you can read results.length as the number of places found (returned by the request, see below). The coverage radius around a latLng or rectangular bounds is set in the request.
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]);
}
}
}

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

Forcing google to give "did you mean" options when using maps/localsearch API

I want my application using Google local search and google maps to give my users the ability to choose from a number of locations when there are a number of possible answers to their query. A good example would be "Overton, UK" - there are lots of places with this name in the country, and the google maps website gives several possible "did you mean results".
The API, however, doesn't give you this information. Both localsearch and GClientGeocoder return one result.
Is there a way to get the API to return a list of possible results?
Have you tried using geocode from google.maps.Geocoder() (version 3 of the Maps API)? I'm pretty sure that it returns an array of results:
var geocoder = new google.maps.Geocoder();
if(geocoder) {
geocoder.geocode({address: address}, function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
//do stuff with results, which is an array of address results
}
else {
//error handling
}
});
}
else {
//error handling
}
More information at Maps API V3 Services. The page goes into detail about the structure of the address results object.