Getting error Geocoder failed while fetching current location using JavaScript - javascript

I am getting the following error while trying to fetch current location using Google Maps API.
Error:
Geocoder failed
I am providing my code below.
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
function getDefaultLocation(){
setTimeout(function(){
var geocoder='';
geocoder = new google.maps.Geocoder();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
codeLatLng(lat, lng)
}
function errorFunction(){
console.log("Geocoder failed");
}
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){
if (results[1]) {
var indice=0;
for (var j=0; j<results.length; j++){
if (results[j].types[0]=='locality'){
indice=j;
break;
}
for (var i=0; i<results[j].address_components.length; i++){
if (results[j].address_components[i].types[0] == "locality") {
city = results[j].address_components[i];
}
if(results[j].address_components[i].types[0] == "administrative_area_level_1"){
region = results[j].address_components[i];
}
if (results[j].address_components[i].types[0] == "country"){
country = results[j].address_components[i];
}
if(results[j].address_components[i].types[0] == "route"){
locality=results[j].address_components[i];
}
}
}
// console.log('final result',city.long_name,region.long_name,country.long_name,locality.long_name);
var city=city.long_name;
var country=country.long_name;
var locality=locality.long_name;
document.getElementById('bindCon').innerHTML=country; document.getElementById('bindCit').innerHTML=city; document.getElementById('bindloc').innerHTML=locality;
}else{
console.log("No results found");
}
}else{
console.log("Geocoder failed due to: " + status);
}
})
}
},5000);
}
The above code is working properly in localhost but while putting this into my testing site (http://xxxx.com) the above error is coming. Here I need to fetch all the required data.

Related

How to pass javascript alert message value to label in asp.net

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;

change Google maps API language

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.

How to get address from lat and lng?

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

Google Map API - Get Address of User

Ive tried several methods to get get a visitors country location using geolocation method but im stil at no avail.
Could someone help atall as I'd like to get a visitors country and write it to a database using ajax.
my current code
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script>
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)
var country = results[7].formatted_address;
$('.location').text(country);
var dataStrings = 'email=<?php echo $userid;?>&location='+ country;
console.log(dataStrinsg);
$.ajax({
type: "POST",
url: "location-update.php",
data: dataStrings,
success: function() {
location.reload();
}
});
return false;
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)
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}</script>
Assuming that you call initalize() before the geocoding(otherwise geocode will be undefined):
You're accessing results[7] here:
var country = results[7].formatted_address;
...but there is no guarantee that results[7] exists.

How can I timeout a google maps geocoder via javascript?

I am very new to javascript and I am having issues with timing out the geocoder requests.
But I am stuck, I tries to add delays into loop, but seems like they don't work.
If you can help, I would appreciarte it.
<script type="text/javascript">
function setLocationOnMap(locs) {
var myOptions = {
zoom: 4,
center: new google.maps.LatLng(locs.lat(), locs.lng()),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
var i=0;
var total='<?php echo $counter ?>';
for (i=0; i<total;i++){//adding cities to map by
var city= document.the_form.elements[i].value;
getLatLong2(city, map, setPointer);
}
}
function setPointer(map, address, locs2){
var position = new google.maps.LatLng(locs2.lat(), locs2.lng());
var marker = new google.maps.Marker({
position: position,
map: map
});
marker.setTitle(address);
}
function initialize() {
var address = "Chicago IL";
getLatLong(address, setLocationOnMap);
}
function getLatLong2(address, map, callback){
var geo = new google.maps.Geocoder;
geo.geocode({'address':address},function(results, status){
if (status == google.maps.GeocoderStatus.OK) {
locs2 = results[0].geometry.location;
callback(map, address, locs2);
} else {
//alert("Geocode was not successful for the following reason: " + status);
}
});
}
function getLatLong(address, callback){
var geo = new google.maps.Geocoder;
geo.geocode({'address':address},function(results, status){
if (status == google.maps.GeocoderStatus.OK) {
// processing...
locs = results[0].geometry.location;
//pausecomp(10000);
callback(locs);
} else {
//alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
When you submit the geocode request, you can start a timer in parallel and when the timer fires, you can declare the request to have timed out. The request will still continue, but you can ignore the results once it has timed out:
function getLatLong(address, callback){
var timerId;
var timedOut = false;
var geo = new google.maps.Geocoder;
geo.geocode({'address':address},function(results, status){
if (timedOut) {
// this request timed out, so ignore results
return;
} else {
// this request succeeded, so cancel timer
clearTimeout(timerId);
}
if (status == google.maps.GeocoderStatus.OK) {
locs = results[0].geometry.location;
callback(locs);
} else {
//alert("Geocode was not successful for the following reason: " + status);
}
});
timerId = setTimeout(function() {
timedOut = true;
alert('Request timed out.');
// do something else
}, 10000);
}

Categories