I'm new to jquery but I am having a bit of a hard time at the moment. This is as far as I can get, the eventual idea is to do the following:
User types in an address and clicks search
Google Geocoder runs
Either error if not result, or grab co-ordinates, state, zip, country, city and print in a message box
The code I have at the moment is not even able to complete the process of grabbing the coordinates from the input box. It keeps telling me it is expecting a bracket but no matter where I put the bracket I cannot get it to run.
This is my trying to run:
http://jsfiddle.net/QA7Xr/16/
Here is the complete code:
var myLatlng = new google.maps.LatLng(31.272410, 0.190898);
// INITALIZATION
function initialize() {
var mapOptions = {
zoom: 4,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
}
// GEOCODE
function codeAddress() {
var address = document.getElementById("address").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
alert("Geocode was successful");
};
} else {
alert("Geocode was not successful for the following reason: " + status);
};
};
}
// GET ADDRESS DETAILS
function getLatLongDetail() {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'latLng': myLatlng
},
function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
var address = "",
city = "",
state = "",
zip = "",
country = "";
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] == '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;
else if (addr.types[0] == ['locality']) // City
city = addr.long_name;
}
alert('City: ' + city + '\n' + 'State: ' + state + '\n' + 'Zip: ' + zip + '\n' + 'Country: ' + country);
}
}
});
}
initialize();
getLatLongDetail();
Can anyone tell me where I am going wrong please? I've hit a dead end with this.
Your JS was a mess, I've tidied it up: http://jsfiddle.net/QA7Xr/19/
In order:
Two extra close brackets in a function
You used getElementById() using an ID that did not exist
You bound an onClick when a JS assignment is easier
Your geocoder var was local within getLatLongDetail. You needed it in codeAddress, so I've made it global.
Points to improve:
Wrap your code in a closure to avoid namespace pollution
Use the Google events to control your code assignments. Right now, if a user clicks too quickly, your code will throw up
Simplify the logic
Here is the updated link,
http://jsfiddle.net/QA7Xr/24/
geocoder.geocode({}, function(){....}); /*not closed properly*/
and there are improper usage of semicolon.
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 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 two set of lat and lng.
I want both address and stored in some variable:
var geocoder = new google.maps.Geocoder();
for(var i=0; i<json_devices.length; i++)
{
var lat = json_devices[i].latitude;
var lng = json_devices[i].longitude;
console.log(lat);
console.log(lng);
var latlng = new google.maps.LatLng(lat,lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
address=results[1].formatted_address;
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
console.log(address);
}
In this, lat & lan get correctly. But address are not stored in variable. What is the mistake?
I am using this method and it is working perfect for me.
Please have a look on it.
public String getAddressFromLatLong(GeoPoint point) {
String address = "Address Not Found";
Geocoder geoCoder = new Geocoder(
getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
point.getLatitudeE6() / 1E6,
point.getLongitudeE6() / 1E6, 1);
if (addresses.size() > 0) {
address =addresses.get(0).getAddressLine(0);
if(address.length()<=0)
address =addresses.get(0).getSubLocality();
}
}
catch (Exception e) {
e.printStackTrace();
}
return address;
}
Here the Google geocode is asynchonous type of function call.
From DOCS:
Accessing the Geocoding service is asynchronous, since the Google Maps
API needs to make a call to an external server. For that reason, you
need to pass a callback method to execute upon completion of the
request. This callback method processes the result(s). Note that the
geocoder may return more than one result.
So you can't get the address like that, instead use the common approach called callback.
Here I have created a sample code to explain the process, which can be altered by yourself.
var geocoder;
function codeLatLng(callback) {
geocoder = new google.maps.Geocoder();
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]) {
address = results[1].formatted_address;
callback(address);
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
$('input[type="button"]').on('click', function () {
codeLatLng(function (address) { //function call with a callback
console.log(address); // THE ADDRESS WILL BE OBTAINED
})
});
JSFIDDLE
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 am sending the google.geocoder several addresses, but the values in the results[0].geometry.location are all the same. I believe I have accounted for the asynchronous nature of the call using a call back. When I add alerts to see the values returned, the addresses passed in the geocoder.geocode( { 'address': addr }... are all correct, the status returned is "ok", but the lat/long are the same for every call. I am not very well versed in JavaScript, and am new to the .net environment, so any help would be greatly appreciated.
This code worked perfectly from 4/1/2012 until some time near December or early 2013. Has something changed with the Google API? I have looked at google's website but cannot find anything.
Here is my initial call:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script type="text/javascript">
var geocoder;
var map;
var directionsDisplay;
var directionsRenderer;
var startPoint;
var endPoint;
function initialize()
{
geocoder = new google.maps.Geocoder();
codeAddress();
var myOptions =
{
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var trafficLayer = new google.maps.TrafficLayer();
trafficLayer.setMap(map);
setMarkers(map);
google.maps.event.addListener(map, 'click', function(event) {
dirMarker(event.latLng);
startPoint = event.latLng;
});
}
function codeAddress()
{
var address = document.getElementById("<%=hCVT.ClientID%>").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
alert("Status: " + status + "res from CODE ADDRESS -- " + results[0].geometry.location); //TO REMOVE
map.setCenter(results[0].geometry.location);
} else {
alert("Geocode of CVT was not successful for the following reason: " + status);
}
});
}
The function to set the markers and info window information (I have removed some of the code that seemed irrelevant to the question)
function setMarkers(map)
{
// Add markers to the map
var shape = {
coord: [1, 1, 1, 20, 18, 20, 18 , 1],
type: 'poly'
};
var places = new Array([,,,,]);
var xx = String;
xx = document.getElementById("<%=addys.ClientID%>").value;
var placeholder = xx.split(",");
var latlng;
var i = 0;
for(var y = 0; y < (placeholder.length / 5 - 1); i=i+5)
{
places[y, 0] = placeholder[i];
places[y, 1] = placeholder[i+1]; //Unit Status
places[y, 2] = placeholder[i+2]; // Long - not used
places[y, 3] = placeholder[i+3]; // Zindex
places[y, 4] = placeholder[i+4]; // HTML for information window
addr = places[y,0];
ustat = places[y,1];
zind = places[y,3];
iwdata = places[y,4];
getLatLong(addr, iwdata, ustat, zind, function(latlng, addr, iwdata, ustat, zind) {
var marker = new google.maps.Marker({
position: latlng,
map: map,
html: iwdata,
icon: pinImage,
shadow: pinShadow,
shape: shape,
title: addr,
zIndex: parseInt(places[y,3])
});
var infowindow = new google.maps.InfoWindow({
content: iwdata});
});
y = y + 1;
}
}
The function where I believe the problem lies follows. Since there were several addresses being sent to google, I added a built in timeout so as to not exceed the limitations. Again, this all worked for about 8 months and has suddenly stopped. Where several markers used to show on the map, now there is one marker which is seeming over written because the lat/lng return is the same as the initial call in the codeAddress() function. In an effort to find a solution I have been adding alerts to show me the return values. I was getting confused with the bugzilla values as they would take me over to the google javascript which was completely over my head.
function getLatLong(addr, iwdata, ustat, zind, callback){
geocoder.geocode( { 'address': addr}, function(results, status){
if (status == google.maps.GeocoderStatus.OK){
callback(results[0].geometry.location, addr, iwdata, ustat, zind);
} else if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
window.setTimeout(function() {self.getLatLong(addr, iwdata, ustat, zind, callback);
},500);
} else {
alert("Address Geocode failure: " + addr + " ==== " + status + "Y value: " + zind + " res ---" + res);
}
});
}
Can anyone help me with this?
Well, after some long hours of staring at this code trying to figure it out, I finally stumbled on something using smartly placed alerts. Apparently the addr variable contained "'" and the geocoder was not able to provide lat/lng data as a result. Adjusted this line:
addr = places[y,0].replace(/'/g, "");
All works now.