How can I timeout a google maps geocoder via javascript? - 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);
}

Related

How to get current location name from longitude and latitude?

I'm using this code to get the current location of the user through google maps api and i am getting the location in the form of latitude and longitudes and getting the location in LatLng variable.
But after that when I am converting the latitude and longitude to an address then its not working.
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (p){
var LatLng = new google.maps.LatLng(p.coords.latitude,p.coords.longitude);
alert(LatLng);
alert(p.coords.latitude);
alert(p.coords.longitude);
var mapOptions = {
center: LatLng,
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'LatLng': LatLng }, function (results, status){
alert(geocoder);
if (status == google.maps.GeocoderStatus.OK){
if (results[1]){
alert("Location: " + results[1].formatted_address);
}
}
});
Firstly as the commentator Parker told, jsp and java tags are irrelevant for your post. I removed it.
You should do the reverse geocoding. The process of doing the converse, translating a location on the map into a human-readable address, is known as reverse geocoding.
Please refer the below google map url for Reverse Geocoding.
See the below snippet of mapping lat & lan to location,
var latlng = {lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1])};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === 'OK') {
if (results[0]) {
map.setZoom(11);
var marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
Let me know if it helps.
$(document).ready(function() {
var currgeocoder;
//Set geo location of lat and long
navigator.geolocation.getCurrentPosition(function(position, html5Error) {
geo_loc = processGeolocationResult(position);
currLatLong = geo_loc.split(",");
initializeCurrent(currLatLong[0], currLatLong[1]);
});
//Get geo location result
function processGeolocationResult(position) {
html5Lat = position.coords.latitude; //Get latitude
html5Lon = position.coords.longitude; //Get longitude
html5TimeStamp = position.timestamp; //Get timestamp
html5Accuracy = position.coords.accuracy; //Get accuracy in meters
return (html5Lat).toFixed(8) + ", " + (html5Lon).toFixed(8);
}
//Check value is present or not & call google api function
function initializeCurrent(latcurr, longcurr) {
currgeocoder = new google.maps.Geocoder();
console.log(latcurr + "-- ######## --" + longcurr);
if (latcurr != '' && longcurr != '') {
var myLatlng = new google.maps.LatLng(latcurr, longcurr);
return getCurrentAddress(myLatlng);
}
}
//Get current address
function getCurrentAddress(location) {
currgeocoder.geocode({
'location': location
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results[0]);
$("#address").html(results[0].formatted_address);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
});
</script>

Getting error Geocoder failed while fetching current location using 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.

Asp.net using javascript, I have taken from Google maps how to save data to the database

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDX1D37MapC2HfewVE0T3MXcUT4bstvHq8&callback=initMap" type="text/javascript"></script>
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></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);
var mapOptions = {
zoom: 15,
center: latlng,
mapTypeControl: true,
navigationControlOptions:
{
style: google.maps.NavigationControlStyle.SMALL
},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(
document.getElementById("mapContainer"), mapOptions
);
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)
}
else {
alert("No results found");
}
}
else {
alert("Geocoder failed due to: " + status);
}
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: "Your Location"
});
});
}
</script>
2-3 hours, I'm looking on the internet and I try, but I did not get results. I'm trying another code block, latitude and longitude can save the database. This is not just what I wanted, and I want to save the city formatted address.
I opened issue in another forum, not responding.
I need a lot of help. Code could bring up here. This issue of homework project.

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

javascript function is returning undefined

I'm trying to implement google maps and the problem I am having is that when I call the function getLatLng, it is returning an undefined value and I can't figure out why.
initialize();
var map;
var geocoder;
function initialize() {
geocoder = new google.maps.Geocoder();
var address = "Rochester, MN";
var myLatLng = getLatLng(address);
console.log("myLatLng = "+myLatLng);
}
function getLatLng(address) {
var codedAddress;
geocoder.geocode({'address': address}, function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
codedAddress = results[0].geometry.location;
console.log("codedAddress 1 = "+codedAddress);
} else {
alert("There was a problem with the map");
}
console.log("codedAddress 2 = "+codedAddress);
});
console.log("codedAddress 3 = "+codedAddress);
return codedAddress;
}
In the firebug console, here is the output that I get in this exact order:
codedAddress 3 = undefined
myLatLng = undefined
codedAddress 1 = (44.0216306, -92.46989919999999)
codedAddress 2 = (44.0216306, -92.46989919999999)
Why is codedAddress 3 and myLatLng showing up first in the console?
geocode is asynchronous (i.e. it sends a request to Google's servers), so you need to pass a callback function to getLatLng, rather than having it return immediately:
function getLatLng(address, callback) {
var codedAddress;
geocoder.geocode({'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
codedAddress = results[0].geometry.location;
console.log("codedAddress 1 = "+codedAddress);
} else {
alert("There was a problem with the map");
}
console.log("codedAddress 2 = "+codedAddress);
callback(codedAddress);
});
}
Here's what I got to work via the Google Maps documentation:
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var address = "Rochester, MN";
var latlng = codeAddress(address);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
function codeAddress(address) {
geocoder.geocode( { 'address': address}, 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
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
Here's a jsFiddle to see it in action. Obviously, you can update this to use jQuery if you need to.
You're missing a closing } for the initialize function.

Categories