I am very new to this and would like to know how to get the full string and not the first character as it is currently doing,
currently using the example of the html + js from https://developers.google.com/maps/documentation/javascript/examples/geocoding-reverse
function codeLatLng(callback) {
var input = document.getElementById('latlng').value;
var latlngStr = input.split(',', 2);
var lat = parseFloat(latlngStr[0]);
var lng = parseFloat(latlngStr[1]);
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
map.setZoom(17);
marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
document.getElementById('Addressb').value= results[0].formatted_address; //working
document.getElementById('Strn').value = results[0].formatted_address[0];
document.getElementById('Strna').value = results[0].formatted_address[2];
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
the results needs to get stored in the specified text fields as bellow
Street Number: <input id="Strn" type="text"><br>
Street Name: <input id="Strna" type="text"><br>
Suburb: <input id="Subu" type="text"><br>
Town: <input id="Town" type="text"><br>
Code: <input id="Code1" type="text"><br>
You have to iterate through the address components and then the types, here is the code
var streetNumber;
var streetName;
var city;
var state;
var zip;
var country;
for(var i = 0; i < results[0].address_components.length; i++){
for(var k = 0; k < results[0].address_components[i].types.length; k++){
if (results[0].address_components[i].types[k] == "street_number")
streetNumber = results[0].address_components[i].long_name;
else if (results[0].address_components[i].types[k] == "route")
streetName = results[0].address_components[i].short_name;
else if (results[0].address_components[i].types[k] == "locality")
city = results[0].address_components[i].long_name;
else if (results[0].address_components[i].types[k] == "administrative_area_level_1")
state = results[0].address_components[i].long_name;
else if (results[0].address_components[i].types[k] == "postal_code")
zip = results[0].address_components[i].long_name;
else if (results[0].address_components[i].types[k] == "country")
country = results[0].address_components[i].long_name;
}
}
Here's a link the Google Maps Geocoding docs, specifying the format of the response.
It looks like it does return the components of the address separately, in the address_components array, in a specific order. So if you're geocoding a street address, address_components[0].long_name should return the street address, address_components[1].long_name the street name, etc.
Hope that helps.
Related
I had implemented geolocation , wherein browser gets location of user.
In this code i'm getting geolocation of user through browser ,but it display location using javascript alert message.
I just want to pass alert message value to label or hiddenfield in ASP.Net & doesn't want to run alert message
My javascript code as follows.
<script type="text/javascript">
var geocoder;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
//Get the latitude and the longitude;
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
codeLatLng(lat, lng)
}
function errorFunction() {
alert("Geocoder failed");
}
function initialize() {
geocoder = new google.maps.Geocoder();
}
function codeLatLng(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results)
if (results[1]) {
//formatted address
alert(results[0].formatted_address)
//find country name
for (var i = 0; i < results[0].address_components.length; i++) {
for (var b = 0; b < results[0].address_components[i].types.length; b++) {
//there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
if (results[0].address_components[i].types[b] == "administrative_area_level_1") {
//this is the object you are looking for
city = results[0].address_components[i];
break;
}
}
}
//city data
alert(city.short_name + " " + city.long_name)
document.getElementById('<%=Label1.ClientID %>').innerHTML = city;
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
</script>
If you want to store the value in a hidden field replace
alert(results[0].formatted_address)
with
//hdnField is the ID of your asp:HiddenField object
var hiddenField = document.getElementById("<%= hdnField.ClientID %>")
hiddenField.value = results[0].formatted_address;
I've a google maps with a draggrabble marker that in infowindow show the street and town
NOw I use this code to get new lng e lat in a form when marker is dragged
var geocoder = new google.maps.Geocoder;
function geocodeLatLng(geocoder, map, infowindow) {
var input = document.getElementById('latlng').value;
var latlngStr = input.split(',', 2);
var latlng = {lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1])};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
if (results[1]) {
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}
google.maps.event.addListener(marker, 'dragend', function (event) {
document.getElementById("lat").value = this.getPosition().lat();
document.getElementById("lng").value = this.getPosition().lng();
document.getElementById("latlng").value = this.getPosition().lat()+','+this.getPosition().lng();
geocodeLatLng(geocoder, map, infowindow);
});
In the input lng, lat, latlng all is ok so the value change moving the marker, but I can determine the value of 2 other input that are city and street
I'm looking for something like
document.getElementById("address").value = this.address;
document.getElementById("city").value = this.city;
The result components contain element organized in this way
results[0].components
filtering n.th result[0].components[n].types by the
route matches long or short name of a route.
locality matches against both locality and sublocality types.
administrative_area matches all the administrative_area levels (administrative_area_level_3.political = town/city , administrative_area_level_2.political = province/county, administrative_area_level_1.political = country)
postal_code matches postal_code and postal_code_prefix.
country matches a country name or a two letter ISO 3166-1 country code.
you can get what you need in
result[0].components[n].long_name
if you want only locality you should iterate this way
for (var i=0; i < results[0].address_components.length; i++ ) {
if (results[0].address_components[i].types == 'locality,political') {
window.alert(results[0].address_components[i].long_name);
};
}
I'm using Azure platform to develop a website.
I'm using in Google maps API to get my location.
The server side is written in C#
I want that Google return the answer in English and not in other language.
How can I do this?
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false" lang="en-us"></script>
<script type="text/javascript">
var geocoder;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
//Get the latitude and the longitude;
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
codeLatLng(lat, lng)
}
function errorFunction() {
alert("Geocoder failed");
}
function initialize() {
geocoder = new google.maps.Geocoder();
}
function codeLatLng(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results)
if (results[1]) {
//formatted address
//alert(results[0].formatted_address)
document.getElementById('<%= citylbl.ClientID %>').value = results[0].formatted_address;
//find country name
for (var i = 0; i < results[0].address_components.length; i++) {
for (var b = 0; b < results[0].address_components[i].types.length; b++) {
//there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
if (results[0].address_components[i].types[b] == "administrative_area_level_1") {
//this is the object you are looking for
city = results[0].address_components[i];
break;
}
}
}
//city data
//alert(city.short_name+" " + city.long_name);
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
</script>
</head>
<body onload="initialize()">
<asp:HiddenField ID="citylbl" runat="server" />
</body>
You need to add a language parameter in you API request.
For example: https://maps.googleapis.com/maps/api/js?language=ja will return information in Japanese.
You can visit this page about Google Maps Language Localization.
Also, the list of supported languages.
I am able to get get full address from current latitude and longitude. but how can I get only city name from full address. this is my code.
var geocoder;
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(latitude, longitude);
//alert("Else loop" + latlng);
geocoder.geocode({
'latLng': latlng
}, function(results, status) {
//alert("Else loop1");
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
var add = results[0].formatted_address;
alert("Full address is: " + add);
} else {
alert("address not found");
}
} else {
//document.getElementById("location").innerHTML="Geocoder failed due to: " + status;
//alert("Geocoder failed due to: " + status);
}
});
var geocoder;
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(latitude, longitude);
geocoder.geocode(
{'latLng': latlng},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
var add= results[0].formatted_address ;
var value=add.split(",");
count=value.length;
country=value[count-1];
state=value[count-2];
city=value[count-3];
alert("city name is: " + city);
}
else {
alert("address not found");
}
}
else {
alert("Geocoder failed due to: " + status);
}
}
);
Split the full address with "," as delimiter and get the city name..
Clean example to get location from lat and lang and parsing result. based on Google Reverse Geocoding
var geocodingAPI = "https://maps.googleapis.com/maps/api/geocode/json?latlng=23.714224,78.961452&key=YOUR_SERVER_API_KEY";
$.getJSON(geocodingAPI, function (json) {
if (json.status == "OK") {
//Check result 0
var result = json.results[0];
//look for locality tag and administrative_area_level_1
var city = "";
var state = "";
for (var i = 0, len = result.address_components.length; i < len; i++) {
var ac = result.address_components[i];
if (ac.types.indexOf("administrative_area_level_1") >= 0) state = ac.short_name;
}
if (state != '') {
console.log("Hello to you out there in " + city + ", " + state + "!");
}
}
});
You can find documentation here :
https://developers.google.com/maps/documentation/geocoding/?hl=fr#ReverseGeocoding
But you can see in your "results" which item is the city without spliting the object.
So you can do :
country=results[0]['address_components'][6].long_name;
state=results[0]['address_components'][5].long_name;
city=results[0]['address_components'][4].long_name;
Be carefull, the numbers "4,5,6" can change by the country. So it safier to test like that :
Getting street,city and country by reverse geocoding using google
Take a look at Google Reverse Geocoding
http://maps.google.com/maps/api/geocode/xml?latlng=YourLatitude,YourLongitude&sensor=false&key=API_KEY
This is already asked here
This is how I I'm doing it. Was afraid to use a comma delimiter.
function ReverseGeoToCity(lat, lng, callback) {
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
var properName = ", ";
for(i=0; i<results[1].address_components.length; i++){
if (results[1].address_components[i].types[0] == "locality")
properName = results[1].address_components[i].short_name + properName;
if (results[1].address_components[i].types[0] == "administrative_area_level_1")
properName += results[1].address_components[i].short_name;
}
callback(properName);
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
}
Below code will help you for get city name From latitude and longitude:
var url = "https://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+long+"&key=KEY_HERE&sensor=false";
$.get(url, function(data) {
var results = data.results;
if (data.status === 'OK')
{
//console.log(JSON.stringify(results));
if (results[0])
{
var city = "";
var address_components = results[0].address_components;
for (var i = 0; i < address_components.length; i++)
{ state = address_components[i].long_name;
}
if (address_components[i].types[0] === "locality" && address_components[i].types[1] === "political" ) {
city = address_components[i].long_name;
}
}
alert("CITY : " + city );
}
else
{
window.alert('No results found');
}
}
else
{
window.alert('Geocoder failed due to: ' + status);
}
});
I have this function that should return the country starting from the latitude and longitude and assign it to a global variable declare outside the function. I know that the a in Ajax stand for asynchronous and I have read every single answer on stackoverflow but I can't fix it.
function getLatLongDetail(myLatlng) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'latLng': myLatlng },
function (results, status) {
var country = "";
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
for (var i = 0; i < results[0].address_components.length; i++) {
var addr = results[0].address_components[i];
// check if this entry in address_components has a type of country
if (addr.types[0] == 'country')
country = addr.long_name;
}
}
return country; // this doesn't work
}
}
});
}
var Country = getLatLongDetail(myLatlng);
alert(Country);// undefined
I know there are hundreds of questions about callback function but none of them worked for me.
Finally I made it! Here the code:
function getLatLongDetail(myLatlng, fn) {
var geocoder = new google.maps.Geocoder();
var country = "";
var city = "";
var address = "";
var zip = "";
var state = "";
geocoder.geocode({ 'latLng': myLatlng },
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
for (var i = 0; i < results[0].address_components.length; i++) {
var addr = results[0].address_components[i];
// check if this entry in address_components has a type of country
if (addr.types[0] == 'country')
country = addr.long_name;
else if (addr.types[0] == ['locality']) // City
city = addr.long_name;
else if (addr.types[0] == 'street_address') // address 1
address = address + addr.long_name;
else if (addr.types[0] == 'establishment')
address = address + addr.long_name;
else if (addr.types[0] == 'route') // address 2
address = address + addr.long_name;
else if (addr.types[0] == 'postal_code') // Zip
zip = addr.short_name;
else if (addr.types[0] == ['administrative_area_level_1']) // State
state = addr.long_name;
}
}
fn(country,city, address, zip, state);
}
});
}
var mCountry; //global variable to store the country
vat mCity; //global variable to store the city
getLatLongDetail(event.latLng, function(country,city, address, zip, state){
mCountry = country; // now mCountry store the value from getLatLongDetail so I can save it in the database
mCity = city;
alert(address + zip + state);
});