API to convert lat lon to NYC neighborhood - google-maps

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

Related

Accessing Maps from Google Apps script bound to form

I’m trying to access Maps from a script bound to a Google form. The problem i’m having is that when debugging the script, it accesses Maps so often that i’m Running into quota limits. I have a Maps API key but do not have a client ID so can’t get Maps.setAuthenication(clientID,Key) to work. I’m doing this for a Scout Troop so don’t want to have to pay to access maps.
Can anyone help?
I was subsequently asked to post my code, and so here it is:
function setLocation(){
var whereString;
var theDuration;
var theDistance;
var theRoute;
var theDirections;
var theTravelString;
// this Sets the Where: Tab on the form
whereString = 'Where: ' + gLocation;
theItemArray = gSignupForm.getItems();
theItemArray[kWhereItem].setTitle(whereString);
//this gets the directions to the location
Maps.setAuthentication('','ABCDEFGHIJKLMNOP');
//Obviously Im'm not going to post the true key
theDirections = Maps.newDirectionFinder()
.setOrigin('7101 Shadeland Ave, Indianapolis, IN 46256')
.setDestination(gLocation)
.setMode(Maps.DirectionFinder.Mode.DRIVING)
.getDirections();
theRoute = theDirections.routes[0];
theDuration = theRoute.legs[0].duration.text;
theDistance = theRoute.legs[0].distance.text;
theTravelString = Utilities.formatString('Travel Considerations: The estimated travel distance is %u miles. ',theDistance);
theTravelString += 'The estimated travel time is ' + theDuration;
theItemArray[kTravelItem].setTitle(theTravelString);
}
One solution to limit the use of low-quota services is to avoid calling those services when the desired information has not changed.
For example, through the use of CacheService, you can dramatically reduce your calls to the Maps API, debugging session or not:
var cache = CacheService.getScriptCache();
function setLocation() {
// Try to find the route for this location if it's still available
var storedRoute = cache.get(gLocation);
if (!storedRoute) {
// No route for this value of the key gLocation was found. Query as normal.
...
theRoute = theDirections.route[0];
// Cache this route for future uses, for the maximum of 6hr).
cache.put(gLocation, JSON.stringify(theRoute), 21600);
} else {
// We have this exact stored route! Convert it from the stored string.
theRoute = JSON.parse(storedRoute);
}
theDuration = ...
...
Your "gLocation" variable may be directly usable as a cache key. If not, you'll need to make it useable by encoding it. The max length key is 250 characters. This single-parameter caching assumes your directions all have a fixed endpoint, as shown in your example code. If both endpoints vary, you'll have to construct a cache key based on both values.
Related question: Maps direction Quota limits

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 v3 returning incorrect lat/lng for South African address

I am plotting a map using south african addresses. This in general works fine but in some instances the API seems unable to find the address and returns the same lat/lng plotted in the centre of the country. I am using the following function to retrieve the coordinates:
function getpointfromaddress(location, callbackfunction){
var geocoderRequest = { address: location, componentRestrictions: {country: 'ZA'} };
geocoder.geocode(geocoderRequest, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var point = results[0].geometry.location
callbackfunction(point)
}
})
}
An example of an address that won't map is "Corner of Witkoppen & Nanyuki Rd,Sunninghill Park,Sandton,2199". The address maps fine using google maps online.
Many thanks for any help you can give.
The problem could be because of the '&' in your address. Calling the address directly from google maps generates the following link.
https://www.google.co.in/maps/search/Corner+of+Witkoppen+%26+Nanyuki+Rd,Sunninghill+Park,Sandton,2199/#-26.029296,28.0215236,14z/data=!3m1!4b1
The '&' is replaced with '%26' in the query.
You can accomplish this in your program by URL encoding the address or by replacing it programmatically in Javascript.

How can I get google maps location names?

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.

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