How to find the nearest cities in Google map API - google-maps

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

Related

give the lat and lng,get the city of radius x mile

when use give a lat and lng ,i should give the city and State of US.
try to use google map place api, but it didn't has the place type
search in google, get some answers :
1.create the database of city data,and use the sql to calculate the distance.but I didn't get any accurate data,and some data are not free.
2.use the third database geoNames,get the data, but I worry the website limit the count of request.
So did you have any answer ,help
If you have lat, and lng, you better got for calling Geocoder.geocode.
Once you get OK in resonse, you can check address_componenets with type "administrative_area_level_n"
var latlng = new google.maps.LatLng(lat, lng);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'latLng': latlng }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
for (var i = 0; i < results[0].address_components.length; i++) {
for (var b = 0; b < results[0].address_components[i].types.length; b++) {
if (results[0].address_components[i].types[b] == "administrative_area_level_2") {
var city = results[0].address_components[i];
}
}
}
}
}

Google Places API nearby search missing places

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

nearbySearch with name specified like wildcard

I am after a way to do a Google Maps API V3 "nearbySearch" by specifying both an exact location but not an exact store name (like a wildcard search).
e.g., If the request was for "Starbucks" in "San Francisco" it would return all Places called "Starbucks", whether the Place had more words in it's title or not e.g., results would contain "Starbucks Coffee", "Starbucks Smith St" or simply "Starbucks". Currently it looks like it only finds identical matches, "Starbucks".
Code (more info here):
var map;
var service;
var infowindow;
function initialize() {
// Specify lat/lng of search location
var SanFran = new google.maps.LatLng(37.777119,-122.41964);
// Create new map object
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: SanFran,
zoom: 15
});
// Create request parametres
var request = {
location: SanFran
, radius: '500',
, name: "Starbucks"
};
// Call the nearby search using the parametres
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
}
// Asynchronous marker creation at returned locations
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]);
}
}
}
I've done some reading and whilst it looks like API3 doesn't offer Wildcard search, I'm hoping there are work arounds.
Thanks in advance!
Sorry all, the answer was really quite simple. I should have been using the textSearch rather than nearbySearch:
...
// Create request parametres
var request = {
location: SanFran
, radius: '500',
, query: "Starbucks"
};
// Call the nearby search using the parametres
service = new google.maps.places.PlacesService(map);
service.textSearch(request, callback);
...
More info here https://developers.google.com/maps/documentation/javascript/places#TextSearchRequests

Find out distance between two points using Google map API based on medium (Road,Air,Ship)? [duplicate]

I have used the google map API to plot a way point on google map
I referred to the the following page:
https://developers.google.com/maps/documentation/javascript/directions
'Using Waypoints in Routes section' and modified it a bit so as to plot only 3 points on the map.
The following is my javascript code.
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var initialloc = new google.maps.LatLng(12.971599, 77.594563);
var mapOptions = {
zoom : 6,
mapTypeId : google.maps.MapTypeId.ROADMAP,
center : initialloc
}
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
directionsDisplay.setMap(map);
calcRoute();
}
function calcRoute() {
var lat = new Array();
var lon = new Array();
var start = new google.maps.LatLng(12.971599,77.594563);
var mid = new google.maps.LatLng(12.971558,77.594552);
var end = new google.maps.LatLng(12.971558,77.594552);
var waypts = [];
waypts.push( {
location : mid,
stopover : true
});
var request = {
origin : start,
destination : end,
waypoints : waypts,
optimizeWaypoints : true,
travelMode : google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(
request,
function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
}
});
}
which works perfectly fine if the 3 locations are within same country, ie they have a road map.
My question is how to plot the map when the location are in different continents eg India and Australia?
Can anyone please help.
Thanks in Advance.
The problem is not about different continents, but whether the routing engine's database has information about all the countries between your start and endpoints, including car ferries. You can see that the same occurs in maps.google.com . Here's an intercontinental route from Europe to India, but if you try to move the B marker to the US or Canada, it doesn't get a route because it doesn't know a ferry across the Atlantic.
You can see what countries have coverage in this spreadsheet.

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);
}
});