for example:
var city, country;
geocoder.geocode(
{'address': city + ', ' + country}, function(results, status) {}
);
the problem is when the var city is wrong and is a random streetname (in a random city)
he puts this location in results, but I only want cities...
Is there a way to use geocode() only for searching a city?
//get address info such as city and state from lat and long
geocoder.geocode({'latLng': latlng}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
//break down the three dimensional array into simpler arrays
for (i = 0 ; i < results.length ; ++i)
{
var super_var1 = results[i].address_components;
for (j = 0 ; j < super_var1.length ; ++j)
{
var super_var2 = super_var1[j].types;
for (k = 0 ; k < super_var2.length ; ++k)
{
//find city
if (super_var2[k] == "locality")
{
//put the city name in the form
main_form.city.value = super_var1[j].long_name;
}
//find county
if (super_var2[k] == "administrative_area_level_2")
{
//put the county name in the form
main_form.county.value = super_var1[j].long_name;
}
//find State
if (super_var2[k] == "administrative_area_level_1")
{
//put the state abbreviation in the form
main_form.state.value = super_var1[j].short_name;
}
}
}
}
}
Related
I have three input array elements and two of them are hidden
defiend in javascript as:
var via_route = document.getElementsByName('via_route[]');
var viaLatitude = document.getElementsByName('via_route_lat[]'); --hidden in form
var viaLongitude = document.getElementsByName('via_route_long[]'); -- hidden elememnt
var viaAutocomplete = new google.maps.places.Autocomplete(inputw,{types:['address']});
//}
viaAutocomplete.addListener('place_changed', function(event) {
var place = viaAutocomplete.getPlace();
if (place.hasOwnProperty('place_id')) {
if (!place.geometry) {
// window.alert("Autocomplete's returned place contains no geometry");
return;
}
console.log('vlonh: '+vlength);
viaLatitude.value = place.geometry.location.lat();
viaLongitude.value = place.geometry.location.lng();
console.log('vlonh2: '+viaLongitude.value);
} else {
service.textSearch({
query: place.name
}, function(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
viaLatitude.value = results[0].geometry.location.lat();
viaLongitude.value = results[0].geometry.location.lng();
}
});
}
});
the value I want to get of all these three above arrays but only getting of via_route element
Edit:
for (var i = 0; i < via_route.length; i++) {
var inputw = via_route[i];
var viaAutocomplete = new google.maps.places.Autocomplete(inputw,{types:['address']});
//}
viaAutocomplete.addListener('place_changed', function(event) {
var place = viaAutocomplete.getPlace();
if (place.hasOwnProperty('place_id')) {
if (!place.geometry) {
// window.alert("Autocomplete's returned place contains no geometry");
return;
}
console.log('vlonh: '+i);
viaLatitude[i].value = place.geometry.location.lat();
viaLongitude[i].value = place.geometry.location.lng();
console.log('vlonh2: '+viaLongitude[i].value);
} else {
service.textSearch({
query: place.name
}, function(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
viaLatitude[i].value = results[0].geometry.location.lat();
viaLongitude[i].value = results[0].geometry.location.lng();
}
});
}
});
}
I think that since it is an array input, you can't directly assign value to it. You need to loop through the array and assign a value.
Example:
Here, I created two array input elements, and one is hidden.
<input type="text" name="arr1[]" style="display:none;">
<input type="text" name="arr2[]">
<p id="val1"></p>
<p id="val2"></p>
Now, I'll assign value through code:
var input1 = document.getElementsByName("arr1[]");
var input2 = document.getElementsByName("arr2[]");
for(var i=0; i < input1.length; i++){
input1[i].value = "10";
document.getElementById("val1").innerHTML = "arr1[] value is: "+input1[i].value;
}
for(var j=0; j < input2.length; j++){
input2[j].value = "20";
document.getElementById("val2").innerHTML = "arr2[] value is: "+input2[j].value;
}
It shows the values as 10,20. Here's the plunker
So, try looping as:
for(var i=0; i < viaLatitude.length; i++){
viaLatitude[i].value = place.geometry.location.lat();
}
for(var j=0; i < viaLongitude.length; j++){
viaLongitude[j].value = place.geometry.location.lng();
}
console.log(viaLatitude[0].value);
console.log(viaLongitude[0].value);
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.
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);
});
I have used the tutorial here http://tech.cibul.net/geocode-with-google-maps-api-v3/ to create a page with map and draggable marker to display address and lat/long.
Demo - http://www.calcunation.com/testgeo.php
How do I captured those results and put them into a php variable so I can insert into a mysql database?
I'm relatively new to Java, and fairly comfortable with PHP.
AJAX would be the cleanest from a user perspective. I'd use jquery $.post to do it http://api.jquery.com/jQuery.post/.
Are you trying to split out the address components?
Like street, city, state, zip....
If so...you'll want to look at the geocoded result, and parse through the array of address types that it returns.
Here is some quick sample code you can use...
//Startup a new geocode instance
var geocoder = new google.maps.Geocoder();
//event.latLng is a latLng object passed into the geocode function to get
your addy results
geocoder.geocode({'location': event.latLng}, function(results, status) {
//Show the results here
console.log(results);
if (status == google.maps.GeocoderStatus.OK) {
var addressResults = results[0].address_components;
var address1 = "";
var address2 = "";
var city = "";
var state = "";
var zipCode = "";
for(var i = 0; i < addressResults.length; i++){
for(var j = 0; j < addressResults[i].types.length; j++){
if(addressResults[i].types[j] == 'street_number'){
address1 = addressResults[i].long_name;
break;
}
if(addressResults[i].types[j] == 'route'){
address1 += " " + addressResults[i].long_name;
break;
}
if(addressResults[i].types[j] == 'subpremise'){
address2 = addressResults[i].long_name;
break;
}
if(addressResults[i].types[j] == 'locality'){
city = addressResults[i].long_name;
break;
}
if(addressResults[i].types[j] == 'administrative_area_level_1'){
state = addressResults[i].short_name;
break;
}
if(addressResults[i].types[j] == 'postal_code'){
zipCode = addressResults[i].long_name;
break;
}
}
}
//Do ajax post to your form here with the data you just parsed out
}
});