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

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

Related

Average Lng/Lat NaN Issues

I'm an amateur programmer and working on a project I have in mind using the google maps API. Long story short, I'm trying to create a variable with the average longitude and latitude of n number of points. I'm to the point that I have an array of the lng/lat coordinates, but I'm struggling to convert them into a format that I can use as input for a google maps LatLng method.
I've referenced this SO question, Find the average (center) of lats/lngs, and numerous other websites for a month now, but I haven't been able to understand or implement a solution. I feel like I'm missing the simple stuff, but I've been banging my head against this for a month, and not getting anywhere. Any advice or help with this would be appreciated.
//GOOGLE MAPS API SCRIPTS
var streetarray = document.getElementsByName("street");
var cityarray = document.getElementsByName("city");
var geocoder;
var map;
var results;
var mapArray = new Array();
var avgLat;
var avgLng;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 8,
//centered on Carrollton, Texas -- Change lat,long values to change initial map area
center:
new google.maps.LatLng(32.999173, -96.897413)
}
//change Id reference to the div/container that contains the google map
map = new google.maps.Map(document.getElementById('map'), mapOptions);
}
function codeAddress() {
//Loop through and concate street and city values to find long,lat values for all fields
for (var cName = 0; cName < namearray.length; cName++){
var address = streetarray[cName].value + cityarray[cName].value;
//start geocode copy & paste text from API reference
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var results = results[0].geometry.location;
map.setCenter(results);
var marker = new google.maps.Marker({
map: map,
position: results,
});
//Push lng/lat locations to the mapArray
mapArray.push(results);
//Loop through mapArray to add Lat/Lng values, and then divide by j (number of locations) to find the average
for (var i in mapArray) {
var avgLat = 0;
var avgLng = 0;
var j = 0;
var avgLat = (avgLat + mapArray[i][1]);
var avgLng = (avgLng + mapArray[i][2]);
console.log(mapArray, avgLat, avgLng);
j++;
}
avgLat = avgLat / j;
avgLng = avgLng / j;
var markerCircle = new google.maps.Circle({
center: results,
radius: 15000,
strokeColor:"#0000FF",
strokeOpacity:0.8,
strokeWeight:2,
fillColor:"#0000FF",
fillOpacity:0.4
})
markerCircle.setMap(map);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}}
2 issues:
results[0].geometry.location is not an array, it's an object(a google.maps.LatLng). Use the methods lat() and lng() to retrieve latitude and longitude
var avgLat = 0;
var avgLng = 0;
var j = 0;.
You must move this to outside of the loop, otherwise the variables will be cleared on each loop.

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

HTML5 - What is making this code get the country instead of city?

What is making the following code get the country and not the city, and how can I change it to get the city instead of country?
function get_visitor_country() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
var lat = position.coords.latitude;
var lon = position.coords.longitude;
var latlng = new google.maps.LatLng(lat, lon);
geocoder = new google.maps.Geocoder();
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
var country = results[results.length-1].formatted_address;
$("#location-detection .location-name").html(country);
$("#geolocation-worked").css("display", "block");
$("#no-geolocation").css("display", "none");
$geolocation_fix.hide().css({ height : 0 });
init_geolocation_switch();
}
}
});
});
}
}
The script is also loading http://maps.google.com/maps/api/js?sensor=false at the end of the file, if that might be affecting it.
Your script currently is not getting anything special(like a city or a country) , it gets something out of the results.
To get the city search inside the results for an entry with types set to ["locality", "political"]
When you found it you got the city.
Creation of an object labeled with addressTypes for convenient access:
var components={};
jQuery.each(results,function(i,v){
components[jQuery.camelCase(v.types.join('-'))]=v;
})
//test it
alert((components.localityPolitical)
? components.localityPolitical.formatted_address
: 'n/a');
See: Address Component Types

Google Map API to detect user location

I am learning about jquery mobile. I came across a sample code which uses the following google maps api
http://maps.google.com/maps/api/js?sensor=false
And the code is to detect the current location of the user
function getPosition(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
var latlng = new google.maps.LatLng(lat, lng);
var geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
//window.alert(results[1].address_components[0].long_name);
var locationVal = results[1].address_components[0].long_name;
var stateVal = results[1].address_components[1].short_name;
var location = document.getElementById('location');
location.value = locationVal;
}
}
});
}
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(getPosition);
}
In the above code, in the results array, there is an address_components array. How to determine the properties of the results object and then again the properties of the address_component?
See here: http://code.google.com/apis/maps/documentation/javascript/geocoding.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);
}
});