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
Related
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
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.
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
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.
I'm using google maps' Interactive Polyline Encoder Utility to plot locations on a map. When I try to plot 31.63089000, 74.87155200, I get an error "Invalid location entered. Must be in range of -90 to 90".
Seems to be a problem with the form code here:
var lat = document.getElementById('txtLatitude').value;
var pLat = parseFloat(lat);
if (pLat.toString() != lat) {
alert('Invalid latitude entered. Must be in range of -90 to 90');
return;
}
It works for me if I truncate your numbers to 31.63089 and 74.871552. The problem in that javascript is that parseFloat is truncating the trailing zeroes off the end. So it converts 31.63089000 to 31.63089. And then 31.63089 is != what was entered in the form, 31.63089000, hence the error. Suggest you file this as a bug with whoever's responsible.