Google Places API nearby search missing places - google-maps

I am attempting to find the nearest building/place name using the Google Places API but have been confused by why some places are not included in the results even if you entered the exact coordinates.
For example, if I searched Google Maps for "UCLA Murphy Hall", google maps is able to find the building and return its Geocode. However, if you entered that Geocode into the Nearby search API, the returned results does not include the building regardless of search radius.
My questions are:
Why is there a difference in what you can search via google maps text search vs what you can get from nearby API?
If I want to be able to find the name of the building from the geocode (34.0715597,-118.4392192), what should I be using?
What is the best approach to map a geocode -> Nearest full street address (with street number) -> nearest building/business?
Thanks in advanced!

Here is some code from an old project of mine reagarding:
What is the best approach to map a geocode -> Nearest full street
address (with street number)
first function gets the nearest street coords based on the lat & lng you provide
second function gets the formatted address of the coords that first function returned
// get nearest coords based on given tracking
tb.prototype.getNearestStreetCoords = function(lat, lng, callback) {
var parentClass = this;
var nearestStreet = {
latitude: lat,
longitude: lng
};
if (parentClass.useNearest != true) callback(nearest);
var request = {
origin: new google.maps.LatLng(lat, lng),
destination: new google.maps.LatLng(lat, lng),
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService = new google.maps.DirectionsService();
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
callback(response);
} else {
callback(false);
}
});
}
// get nearest formatted address based on lat & lng
tb.prototype.getAddress = function(lat, lng, callback) {
geocoder = new google.maps.Geocoder();
geocoder.geocode({'latLng': new google.maps.LatLng(lat, lng)}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
callback(results[0].formatted_address);
} else {
callback(false);
}
});
}
UPDATE
Distance calculation function, between 2 lat - lng points written in php.
function distance($lat1, $lon1, $lat2, $lon2, $unit = 'M') {
$theta = $lon1 - $lon2;
$dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
$dist = acos($dist);
$dist = rad2deg($dist);
$miles = $dist * 60 * 1.1515;
$unit = strtoupper($unit);
if ($unit == 'K') {
return ($miles * 1.609344);
} else if ($unit == 'N') {
return ($miles * 0.8684);
} else {
return $miles;
}
}

For turning geocodes into full street addresses, I'd suggest you try our Reverse Geocoding service. Using the above location coordinates, reverse geocoding returns "410 Charles E Young Drive, UCLA, Los Angeles, CA 90024, USA"
Documentation: https://developers.google.com/maps/documentation/geocoding/#ReverseGeocoding
Example request: http://maps.googleapis.com/maps/api/geocode/json?latlng=34.0715597,-118.4392192&sensor=true_or_false

Related

different results between map.google.com and google api for javascript

i'm making simple website that helps to find direction between 2 points.
and i found something strange.
if i search through map.google.com it returns exact results, but mine dose not.
for example, i set "New York University, New York, NY, United States" as origin and "260 Broadway New York NY 10007" as destination using map.google.com
using map.google.com
if i use my website using googleMap API->
using api
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDs8SYxRh-pMXa9Qe-K1nVY0g3CLpmJ9mo&signed_in=true&libraries=places&callback=initMap" async defer></script>
function calculateAndDisplayRoute(directionsDisplay, directionsService,
markerArray, stepDisplay, map) {
for (var i = 0; i < markerArray.length; i++) {
markerArray[i].setMap(null);
}
directionsDisplay.setPanel(document.getElementById('panel'));
var selectedMode = document.getElementById('mode').value;
directionsService.route({
origin: document.getElementById('pac-input').value,
destination: document.getElementById('pac-input2').value,
travelMode: google.maps.TravelMode[selectedMode]
}, function(response, status) {
// Route the directions and pass the response to a function to create
// markers for each step.
if (status === google.maps.DirectionsStatus.OK) {
document.getElementById('warnings-panel').innerHTML =
'<b>' + response.routes[0].warnings + '</b>';
directionsDisplay.setDirections(response);
//showSteps(response, markerArray, stepDisplay, map);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
It looks like you have places autocomplete inputs and read value of these inputs in your code.
I can suggest using the place ID from places autocomplete in your directions service. This way you will be sure that you work with the address that was chosen.
Look at this example and type there your addresses http://jsbin.com/xuyisem/1/edit?html,output

google maps api can't find one specific address

I am using google maps api and it works for all but one specific address. It's "99p Stores 19-20 Market Place Wisbech PE13 1DZ". When using google maps I can find it, but using js api it says 'zero results'.
My code:
function mapsSetMark(map, address) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': address}, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
map.setZoom(13);
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
console.log('Geocode was not successful for the following reason: ' + status);
}
});
}
"99p Stores 19-20 Market Place Wisbech PE13 1DZ" is a place not a postal address. The Geocoder is specifically for postal addresses
It can find "19-20 Market Place Wisbech PE13 1DZ"
To find "99p Stores 19-20 Market Place Wisbech PE13 1DZ" use the Places API Library

How to find the nearest cities in Google map API

I want to find the nearest cities in the Australia which city i gave for example In this look out the examples. I tried wit h Google API but no use .How can i achieve like this. Could you help me?
code is
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var request = {
location: fenway,
radius: 500,
types: ['store']
};
var service = new google.maps.places.PlacesService(map);
service.search(request, callback);
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var lat = results[i].geometry.location.lat();
var geocoder = new google.maps.Geocoder();
var lng = results[i].geometry.location.lng();
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({
'latLng': latlng
}, function (result, status1) {
if (status == google.maps.GeocoderStatus.OK) {
if (result[1]) {
console.log(result[1]);
}
} else {
alert("Geocoder failed due to: " + status1);
}
});
}
}
}
I want near cities not like the stores etc. I have to find the suburbs in the Australia what are near to the suburb which i given
I've written a code snippet that allows you to retrieve all nearby cities by combining the Google Maps Geocoding API and GeoNames.org API (besides a file_get_contents your could also do a cURL request).
/*
* Get cities based on city name and radius in KM
*/
// get geocode object as array from The Google Maps Geocoding API
$geocodeObject = json_decode(file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address={CITY NAME},{COUNTRY CODE}'), true);
// get latitude and longitude from geocode object
$latitude = $geocodeObject['results'][0]['geometry']['location']['lat'];
$longitude = $geocodeObject['results'][0]['geometry']['location']['lng'];
// set request options
$responseStyle = 'short'; // the length of the response
$citySize = 'cities15000'; // the minimal number of citizens a city must have
$radius = 30; // the radius in KM
$maxRows = 30; // the maximum number of rows to retrieve
$username = '{YOUR USERNAME}'; // the username of your GeoNames account
// get nearby cities based on range as array from The GeoNames API
$nearbyCities = json_decode(file_get_contents('http://api.geonames.org/findNearbyPlaceNameJSON?lat='.$latitude.'&lng='.$longitude.'&style='.$responseStyle.'&cities='.$citySize.'&radius='.$radius.'&maxRows='.$maxRows.'&username='.$username, true));
// foreach nearby city get city details
foreach($nearbyCities->geonames as $cityDetails)
{
// do something per nearby city
}
be carefull with your requests amount because the API's are limited
For more information about the API's visit the following url's:
https://developers.google.com/maps/documentation/geocoding/intro#GeocodingResponses
http://www.geonames.org/export/web-services.html

How to geocode an address into lat/long with Google maps

I want to be able to plot several companies on a google map and understand I need to geocode these.
I also have the code below that plot's multiple markers on a map.
How can I Geocode several company addresses (using the following address as the first example) and incorporate it into the current code I have?
I really need someone's help as I can't make sense of the Google documentation as well as incorporating it with what I already have.
you could use google's geocoding to obtain coordinates of your post codes
EDIT: I don't really like you changing the sense of the question like that but ok. Please try sth like that (its not tested):
// Creating an array that will contain the coordinates
// for New York, San Francisco, and Seattle
var places = [];
// Adding a LatLng object for each city
//places.push(new google.maps.LatLng(40.756, -73.986));
//places.push(new google.maps.LatLng(37.775, -122.419));
//places.push(new google.maps.LatLng(47.620, -122.347));
//places.push(new google.maps.LatLng(-22.933, -43.184));
var result;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "http://maps.googleapis.com/maps/api/geocode/json?address=your+code&sensor=false",true);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
result = eval('(' + xmlhttp.responseText + ')');
if (result.status == "OK") {
var location = new google.maps.LatLng(result.results[0].geometry.location.lat, result.results[0].geometry.location.lng);
places.push(location);
this should probably work, despite possible minor errors.
EDIT2: I have just now found simpler solution:
// Creating an array that will contain the coordinates
// for New York, San Francisco, and Seattle
var places = [];
// Adding a LatLng object for each city
//places.push(new google.maps.LatLng(40.756, -73.986));
//places.push(new google.maps.LatLng(37.775, -122.419));
//places.push(new google.maps.LatLng(47.620, -122.347));
//places.push(new google.maps.LatLng(-22.933, -43.184));
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': "your+code"}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
//var marker = new google.maps.Marker({
//map: map,
//position: results[0].geometry.location
//});
places.push(results[0].geometry.location);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});

How to geocode in google maps v3

I've been looking through version 3 of the google maps api, and I have put together a small script to geocode an address. The problem is that I want to see If i can extract the lat lng without having to 'split()' the result.
function getLatLng() {
var geocoder = new google.maps.Geocoder();
var query = "12 henry street, dublin 1, dublin, ireland";
var address = query;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latLng = results[0].geometry.location;
alert('Geocode succesful ' + latLng);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
I want to get the lat and the lng from the var latLng.
Can this be done without calling latLng.split(',');?
Thanks so much for your help
Never use internal variables exposed by the API. They can and do change from release to release. Always use documented methods.
results[0].geometry.location is a LatLng object, so use the relevant methods:
var lat=results[0].geometry.location.lat();
var lng=results[0].geometry.location.lng();
You can use this:
var lat= results[0].geometry.location.lat();
var lng= results[0].geometry.location.lng();
alert(lat);
alert(lng);