How do I call function inside jQuery .each?
At the moment my function is performed only the last time.
How can I edit this to execute every time the function MyCurrentPosition(dsRow) is called?
This is the code:
Maps.GetCoordinates = function (jsonResponse) {
jQuery.each(jsonResponse, function(filterName,result) {
var risultati = result;
var items = risultati.rows;
//console.log (risultati.total);
if(risultati.total > 0)
{
jQuery.each(items, function(i,dsRow) {
var myhtml= dsRow.latitude;
//This work all time
jQuery('#show_distance_'+dsRow.id).html(myhtml).show();
//but this function only last time print result
MyCurrentPosition(dsRow);
});
}
}); //end foreach
}
EDIT: This is the MyCurrentPosition function :
var options = { enableHighAccuracy: true, timeout: 12000, maximumAge: 0 };
function MyCurrentPosition(dsRow) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (pos) {
crd = pos.coords;
HelloMapsSearch.GetDistance(crd,dsRow);
},
showError,
options );
} else {
alert("Geolocation is not supported by your device.");
}
//return crd;
}
HelloMapsSearch.GetDistance = function (crd,dsRow) {
var origine = crd;
var destinazione = dsRow;
var mxstart = new google.maps.LatLng(origine.latitude,origine.longitude);
var mxend = new google.maps.LatLng(destinazione.latitude, destinazione.longitude);
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [mxstart],
destinations: [mxend],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
//}, callback );
}, function(response, status) {callback(response, status, dsRow)});
}
function callback(response, status, dsRow) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var outputDiv = document.getElementById('show_distance_'+dsRow.id);
outputDiv.innerHTML = '';
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
outputDiv.innerHTML += "Origine:"+origins[i] + '<br> to destinazione:' + destinations[j] + '<br>'
+ ': ' + results[j].distance.text + ' in '
+ results[j].duration.text + '<br>';
}
}
}
}
A few things to check out. jsonResponse must be an array. risultati must also have rows that is of type Array.
As for the function inside called MyCurrentPosition, we are currently missing on the implementation itself.
Does it have an if inside that prevents logging? Share the code please.
Related
As my loop is so fast, the intervals are overlapping and not able to stop one timerId. here is my code:
data = ['115536', '117202']; // BARCODES AVAILABLE ON A4 SHEET //
var scan_delay = 500; // USER AVG SCANNING SPEED PER BARCODE //
var timerId;
var scannedItemsList = []; // ITEMS WHICH ARE SCANNED BY SEEING A4 SHEET BY THE USER //
var tableDataList = []; // TO SHOW DATA WHICH WE GOT FROM API //
Jbin
try {
var data = ['115536', '117202']; // BARCODES AVAILABLE ON A4 SHEET //
var scan_delay = 500; // USER AVG SCANNING SPEED PER BARCODE //
var timerId;
var scannedItemsList = []; // ITEMS WHICH ARE SCANNED BY SEEING A4 SHEET BY THE USER //
var tableDataList = []; // TO SHOW DATA WHICH WE GOT FROM API //
execute(data);
function execute(data) {
var i = 0;
scanSimulatorWithADelay(data, i);
}
function scanSimulatorWithADelay(data, i) {
setTimeout(function () {
getJobDetailsByCallingAPI(data[i], i);
i++;
if (data.length > i) {
scanSimulatorWithADelay(data, i);
} else {
i = 0;
}
}, scan_delay);
}
function getJobDetailsByCallingAPI(jobNumber, index) {
scannedItemsList.push(jobNumber);
//poll_for_jobs_count_which_are_scanned_but_waiting_to_add_to_table
startPolling();
//Simulate API to get response after every 3 seconds//
var apiDelay = (index + 1) * 3000;
setTimeout(function () {
console.log('API CALLED AT ' + new Date().toLocaleTimeString());
CallTheAPI(jobNumber);
}, apiDelay);
}
function CallTheAPI(jobNumber) {
console.log("JOB NO " + jobNumber + " API response Recd");
tableDataList.push(jobNumber);
}
function startPolling() {
var pollStatus = '';
timerId = setInterval(() => {
debugger;
console.log('timerId when starting interval ' + timerId);
var jobsWhichAreScannedButNotLoaded = jobsWhichAreScannedButNotLoadedStill();
console.log("$$$$$$ jobsWhichAreScannedButNotLoaded = " + jobsWhichAreScannedButNotLoaded.length);
if (jobsWhichAreScannedButNotLoaded.length === 0) {
console.log("### Inteval Cleared ### " + timerId);
//CLEAR TIMER
clearInterval(timerId);
} else {
pollStatus = 'Polling inprogress and the pollID ' + timerId;
}
console.log('####' + pollStatus);
}, 2000);
}
function jobsWhichAreScannedButNotLoadedStill() {
let stillLoadingJobs = [];
scannedItemsList.forEach(scannedItemsListJobNumber => {
let foundJobInsideTable = false;
if (scannedItemsListJobNumber) {
foundJobInsideTable = tableDataList.indexOf(scannedItemsListJobNumber) > -1;
if (!foundJobInsideTable) {
stillLoadingJobs.push(scannedItemsListJobNumber);
}
}
}); // End of scannedItemsList forEach loop
if (stillLoadingJobs.length > 0) {
return stillLoadingJobs;
}
return [];
}
} catch (error) { throw error; }
Your timer_id variable is on the global scope and hence overwritten every time you call startPolling.
So when you'll call clearInterval(timer_id), timer_id will be the id of the last setInterval, and the first one will keep running endlessly.
Simply add a var in your startPolling function so that timer_id be scoped correctly, and that it doesn't get overwritten by next call.
try {var data = ['115536', '117202'];
var scan_delay = 500;
// remove this one
//var timerId;
var scannedItemsList = [];
var tableDataList = [];
execute(data);
function execute(data) {
var i = 0;
scanSimulatorWithADelay(data, i);
}
function scanSimulatorWithADelay(data, i) {
setTimeout(function () {
getJobDetailsByCallingAPI(data[i], i);
i++;
if (data.length > i) {
scanSimulatorWithADelay(data, i);
} else {
i = 0;
}
}, scan_delay);
}
function getJobDetailsByCallingAPI(jobNumber, index) {
scannedItemsList.push(jobNumber);
//poll_for_jobs_count_which_are_scanned_but_waiting_to_add_to_table
startPolling();
//Simulate API to get response after every 3 seconds//
var apiDelay = (index + 1) * 3000;
setTimeout(function () {
console.log('API CALLED AT ' + new Date().toLocaleTimeString());
CallTheAPI(jobNumber);
}, apiDelay) ;
}
function CallTheAPI(jobNumber) {
$.ajax({
url: "https://jsonplaceholder.typicode.com/todos/1",
type: "GET",
async: true,
success: function (response) {
console.log("JOB NO " + jobNumber + " API response Recd");
tableDataList.push(jobNumber);
}
});
}
function startPolling() {
var pollStatus = '';
/////////
///HERE
/////////
// Declare timerId in startPolling scope
/////////
var timerId = setInterval(() => {
debugger;
console.log('timerId when starting interval '+ timerId);
var jobsWhichAreScannedButNotLoaded = jobsWhichAreScannedButNotLoadedStill();
console.log("$$$$$$ jobsWhichAreScannedButNotLoaded = "+ jobsWhichAreScannedButNotLoaded.length);
if (jobsWhichAreScannedButNotLoaded.length === 0) {
console.log("### Inteval Cleared ### "+ timerId);
//CLEAR TIMER
clearInterval(timerId);
} else {
pollStatus = 'Polling inprogress and the pollID ' + timerId;
}
console.log('####' + pollStatus);
}, 2000);
}
function jobsWhichAreScannedButNotLoadedStill() {
let stillLoadingJobs = [];
scannedItemsList.forEach(scannedItemsListJobNumber => {
let foundJobInsideTable = false;
if (scannedItemsListJobNumber) {
foundJobInsideTable = tableDataList.indexOf(scannedItemsListJobNumber) > -1;
if (!foundJobInsideTable) {
stillLoadingJobs.push(scannedItemsListJobNumber);
}
}
}); // End of scannedItemsList forEach loop
if (stillLoadingJobs.length > 0) {
return stillLoadingJobs;
}
return [];
}
} catch (error) { throw error; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I created a small test project in here: http://jsfiddle.net/jochenhebbrecht/k3a3fvq0/3/
I clean routes using the following method:
// Clean previous routes
if (directionsDisplays.length > 0) {
for(var i = 0; i < directionsDisplays.length; i++) {
directionsDisplays[i].setMap(null);
}
directionsDisplays.length = 0;
}
I draw routes using the follow method:
// Draw all routes
if (routes.length > 0) {
for (var i = 0; i < routes.length; i++) {
(function(i){
var route = routes[i];
var request = {
origin: route.origin,
destination: route.destination,
travelMode: google.maps.TravelMode.WALKING,
waypoints: route.waypoints
};
var directionsDisplay = new google.maps.DirectionsRenderer({
suppressMarkers: true,
preserveViewport: true,
polylineOptions: {
strokeColor: '#C6D300'
}
});
directionsDisplay.setMap(map);
directionsDisplays.push(directionsDisplay);
directionsService.route(request, function (result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
})(i);
}
}
I have a checkbox which show some routes on a map. If you check the box, routes are shown. If you uncheck the box, routes are removed.
However, if I check the box again (for a second time), not all routes are rendered correctly. You have to check/uncheck a couple of times to let it work ...
Any idea what I'm doing wrong?
Check the status returned by your directions requests. If they fail due to OVER_QUERY_LIMIT, delay a short while and retry the failed requests.
Also, don't request the routes every time they are displayed, if they are already available redisplay the route.
Note that the approach above will only work for the same order of magnitude of routes you currently have, if you have a lot more routes it will be prohibitively slow.
proof of concept fiddle
function highlightRoutes() {
if (directionsDisplays.length > 0 && (directionsDisplays[0].getMap() == null)) {
// redisplay the routes
for (var i = 0; i < directionsDisplays.length; i++) {
directionsDisplays[i].setMap(map);
}
} else if (directionsDisplays.length > 0 && (directionsDisplays[0].getMap() != null)) {
// hide the routes
for (var i = 0; i < directionsDisplays.length; i++) {
directionsDisplays[i].setMap(null);
}
} else {
var routes = new Array();
if (jQuery('#chkBxBikeRoutes').attr('checked')) {
routes.push.apply(routes, getBikeRoutes());
}
// Clean previous routes
if (directionsDisplays.length > 0) {
for (var i = 0; i < directionsDisplays.length; i++) {
directionsDisplays[i].setMap(null);
}
directionsDisplays.length = 0;
}
// Draw all routes
if (routes.length > 0) {
for (var i = 0; i < routes.length; i++) {
(function(i) {
var route = routes[i];
var request = {
origin: route.origin,
destination: route.destination,
travelMode: google.maps.TravelMode.WALKING,
waypoints: route.waypoints
};
var directionsDisplay = new google.maps.DirectionsRenderer({
suppressMarkers: true,
preserveViewport: true,
polylineOptions: {
strokeColor: '#C6D300'
}
});
directionsDisplay.setMap(map);
directionsDisplays.push(directionsDisplay);
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
} else if (status == google.maps.DirectionsStatus.OVER_QUERY_LIMIT) {
//document.getElementById("status").innerHTML += request.origin+":"+request.destination+"status:"+status+"<br>";
setTimeout(function() {
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
} else {
document.getElementById("status").innerHTML += request.origin + ":" + request.destination + "status:" + status + "<br>";
}
})
}, 2000);
} else {
document.getElementById("status").innerHTML += request.origin + ":" + request.destination + "status:" + status + "<br>";
}
});
})(i);
}
}
}
}
Unfortunately you cannot do that.
Update your code as shown below and you will see what happens:
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
} else {
alert(status);
}
You will get several OVER_QUERY_LIMIT status messages.
More information can be found here:
https://developers.google.com/maps/documentation/business/articles/usage_limits
https://developers.google.com/maps/documentation/javascript/directions#DirectionsStatus
Can anyone tell me why the map does not load centered the first time it loads? It works fine when I do a second search, but never loads up correctly the first time.
src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"
var directionsDisplay;
var directionsService;
var geocoder;
var currentAddress = 'placeholder';
var tabCount = 0;
var altRouteCount = 0;
var savedRoutes;
$(document).ready(function(){
$('#message-container').hide (0);
document.getElementById('sidebar').className = 'sidebar-hidden';
// Keeps form pointAB from refreshing the page.
$('#pointAB').on('submit', function (e) {
e.preventDefault();
});
$('#tabs').tab();
$('#tabs a').click( function (e) {
e.preventDefault();
$(this).tab('show');
});
$('#sidebar #togglebtn').click(toggleSidebar);
$('#deletes').click(deleteTabs);
$('#routeChange').click(function () {
var index = $('#routeChange').data('route');
index = (index+1)%altRouteCount;
deleteTabs();
printRoute (savedRoutes, index);
$('#routeChange').data('route', index);
});
// Call Google Direction
directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer();
// Google Autocomplete
var start_input = document.getElementById('start');
var end_input = document.getElementById('end');
var bounds = new google.maps.LatLngBounds(
new google.maps.LatLng(40.532980, -74.118551),
new google.maps.LatLng(40.895218, -73.735403)
);
// Bounds right now only restrict country
var start_autocomplete = new google.maps.places.Autocomplete((start_input),{
// bounds: {sw:new google.maps.LatLng(40.895218, -73.735403), ne:new google.maps.LatLng(40.532980, -74.118551)},
componentRestrictions: {country: 'us'}
}
);
var end_autocomplete = new google.maps.places.Autocomplete((end_input),{
// bounds: {sw:new google.maps.LatLng(40.895218, -73.735403), ne:new google.maps.LatLng(40.532980, -74.118551)},
componentRestrictions: {country: 'us'}
}
);
start_autocomplete.setBounds(bounds);
end_autocomplete.setBounds(bounds);
// Initial map
function initialize() {
var map;
var pos;
// Default pos for map will be center of Manhattan
if(!pos){
pos = new google.maps.LatLng(40.784148400000000000, -73.966140699999980000);
}
var mapOptions = {
zoom: 13
};
getAddress();
// Draw Map
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
map.setCenter(pos);
// Google Direction text route
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions-panel'));
//Needed to resize maps
google.maps.event.addDomListener (map, 'idle', function(){
google.maps.event.trigger (map, 'resize');
});
}
// Load Map
google.maps.event.addDomListener(window, 'load', initialize);
});
/************************************************
Site Navigational Elements
************************************************/
function toggleSidebar() {
var state = $('#sidebar').data('toggle');
if (state == 'hidden') {
document.getElementById('sidebar').className = "sidebar-appear";
$('#sidebar').data('toggle', 'shown');
}
else if (state == 'shown') {
document.getElementById('sidebar').className = "sidebar-hidden";
$('#sidebar').data('toggle', 'hidden');
}
};
function nextSlide() {
$('#navCarousel').carousel('next');
};
function prevSlide(){
$('#navCarousel').carousel('prev');
};
/************************************************
UI Messages
************************************************/
function hideMessage(){
$('#init-message').hide(1000);
};
function pushMessage (messageType, message) {
$('#message-container').hide (0);
if (messageType == 'error') {
document.getElementById('message-container').className = "alert alert-danger";
document.getElementById('icon').className = "glyphicon glyphicon-remove-sign";
}
else if (messageType == 'success') {
document.getElementById('message-container').className = "alert alert-success";
document.getElementById('icon').className = "glyphicon glyphicon-ok-sign";
}
else if (messageType == 'warn') {
document.getElementById('message-container').className = "alert alert-warning";
document.getElementById('icon').className = "glyphicon glyphicon-exclaimation-sign";
}
else {
//Congrats. Senpai has noticed your ability to break shit. Rejoice.
console.error ("Please check your messageType.")
}
$('#message').text(message);
$('#message-container').show (1000);
};
/************************************************
Information Retrieval
************************************************/
// Get current location button function
function getAddress(callback){
geocoder = new google.maps.Geocoder();
// If geolocation available, get position
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successCallback, errorCallback, {timeout:60000,maximumAge:60000});
}
//Else, browser doesn't support geolocaiton
else {
pushMessage ('error', 'Your browser doesn\'t support geolocation.');
console.log("Browser doesn't support geolocaiton");
}
// Optional callback
if (callback){
callback();
}
};
function successCallback(position){
var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
//Reverse geocoding for current location
geocoder.geocode({'latLng': pos}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results.length != 0) {
currentAddress = results[0].formatted_address;
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
};
function errorCallback(){
};
fillAddress = function() {
if (currentAddress != 'placeholder') {
$('#start').val (currentAddress);
pushMessage ('success', "Got your current location!");
}
else {
pushMessage ('warn', 'Please share your location to use this feature.');
}
};
// Set route and request direction result
function calcRoute() {
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
if (start == '' && end == '') {
pushMessage ('error', "Please fill in your current location and destination.");
start='';
end='';
return;
}
else if (start == '') {
pushMessage ('error', "Please fill in your current location.");
start='';
end='';
return;
}
else if (end == '') {
pushMessage ('error', "Please fill in your destination.");
start='';
end='';
return;
}
else {
start += ' new york city';
end += ' new york city';
}
var request = {
origin: start,
destination: end,
provideRouteAlternatives: true,
travelMode: google.maps.TravelMode.TRANSIT
};
deleteTabs();
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
altRouteCount = response.routes.length;
savedRoutes = response;
printRoute (savedRoutes, 0);
//Move to next slide when directions have been retrieved.
$('#navCarousel').carousel('next');
//Disable loading icon pseudocode.
//$('#loadingIcon').hide(300);
savedRoutes = response;
}
else {
//If DirectionsStatus.NOT_FOUND
//or DirectionsStatus.ZERO_RESULTS
pushMessage ('error', 'No directions found.');
}
});
};
function printRoute (routeObj, routeNo) {
// Get route object
var thisRoute = routeObj.routes[routeNo].legs[0];
for (var i = 0; i < thisRoute.steps.length; i++) {
// Find all possible transit
if (typeof thisRoute.steps[i].transit != 'undefined'
&& thisRoute.steps[i].transit.line.vehicle.type == "SUBWAY") {
trainTab (thisRoute.steps[i]);
}
}
}
//Get details from Maps API json object
function getTransitDetail(obj, tabNo){
var parent='';
if (tabNo) {
parent='div#tab'+tabNo+' ';
}
$(parent+'#train').text(obj.transit.line.short_name + " Train");
$(parent+'#train-stop-depart').text(obj.transit.departure_stop.name);
$(parent+'#train-stop-end').text(obj.transit.arrival_stop.name);
$(parent+'#num-stop').text(obj.transit.num_stops + " Stops");
$(parent+'#arrival_time').text(obj.transit.arrival_time.text);
$(parent+'#departure_time').text(obj.transit.departure_time.text);
$(parent+'#distance').text(obj.distance.text);
$(parent+'#duration').text(obj.duration.text);
};
// Get current time from device
function getTime(){
var currentdate = new Date();
var datetime = currentdate.getDate() + "/"
+ (currentdate.getMonth()+1) + "/"
+ currentdate.getFullYear() + " # "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds();
return datetime;
};
function makeNewTab() {
var prevTab = 'tab' + tabCount;
tabCount++;
var newTab = 'tab' + tabCount;
console.log ('New Tab.');
//Adds tab to nav bar
$('#routeChange').before('<li>TAG LABEL</li>');
//Adds contents of tab
$('div.tab-content #'+prevTab).after('<div id="'+newTab+'"></div>');
$('#'+newTab).addClass("tab-pane");
};
function deleteTabs() {
var thisTab;
while (tabCount >= 1) {
thisTab = 'tab' + tabCount;
//Remove tab from nav bar
$('ul#tabs li a[href="#'+thisTab+'"]').remove();
//Remove contents of tab
$('#'+thisTab).remove();
tabCount--;
}
tabCount = 1;
$('#tabs a:first').tab('show');
};
function trainTab (obj) {
makeNewTab();
$('ul#tabs li a[href="#tab'+tabCount+'"]').text(obj.transit.line.short_name);
$('#tab'+tabCount).append (
'<div id="station-info" class="col-xs-11 col-xs-height col-sm-12 col-sm-height">\
<p>Station Info:</p>\
<p id="train"></p>\
<p id="train-stop-depart"></p>\
<p id="train-stop-end"></p>\
<p id="num-stop"></p>\
<p id="arrival_time"></p>\
<p id="departure_time"></p>\
<p id="distance"></p>\
<p id="duration"></p>\
<!-- <%= link_to "an article", #station%> -->\
</div>');
getTransitDetail (obj, tabCount);
};
Is it because of the order of my code? I tried playing around with the order and could not find a solution. Any help would be appreciated. Thanks in advance!
Hi I have a button which when it gets clicked triggers a function. The function does some stuff (reverse geocodes a latitude/longitude) and then fills a hidden form input with a value.
I need the input to have the correct value before the rest of the code I need gets executed, is there a way to do this? At the moment I have
$('.addButton').click(function() {
//first run the reverse geocode to update the hidden location input with the readable address
reversegeocode();
var location = $("#location").val();//the value I need
$.post("<?php echo $this->webroot;?>locations/add", {location:location})
.done(function (data) {
$("#locationsHolder").html(data);
});
});
So basically I don't want to get the value from the input and post it via AJAX until I know that the reversegeocode() function has finished
Can anyone please explain how I can go about this. I've read some stuff about deferment but I'm absolutely useless at figuring out Javascript and I'm really struggling.
Thanks
EDIT:
Here's my reversegeocode funciton
function reversegeocode(){
var lat = $('#lattitude').val();
var lng = $('#longitude').val();
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {//http://stackoverflow.com/questions/8082405/parsing-address-components-in-google-maps-upon-autocomplete-select
var address_components = results[0].address_components;
var components={};
jQuery.each(address_components, function(k,v1) {jQuery.each(v1.types, function(k2, v2){components[v2]=v1.long_name});})
var output = '';
var needAcomma = false;
if(components.route != undefined) {
output += components.route;
needAcomma = true;
}
if(components.locality != undefined) {
if(needAcomma) {
output += ', ';
}
output += components.locality;
needAcomma = true;
}
if(components.administrative_area_level_1 != undefined) {
if(needAcomma) {
output += ', ';
}
output += components.administrative_area_level_1;
needAcomma = true;
}else if(components.administrative_area_level_2 != undefined) {
if(needAcomma) {
output += ', ';
}
output += components.administrative_area_level_2;
needAcomma = true;
}else if(components.administrative_area_level_3 != undefined) {
if(needAcomma) {
output += ', ';
}
output += components.administrative_area_level_3;
needAcomma = true;
}
$("#location").val(output);
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
}
Since reversegeocode is a asynchronous method, you need to use a callback based solution. reversegeocode should receive a callback method as a argument and then invoke the callback once the geocoding is completed.
$('.addButton').click(function () {
//pass a callback to reversegeocode which will get called once the geocoding is completed
reversegeocode(function (location) {
//the callback receives the location as a parameter
$.post("<?php echo $this->webroot;?>locations/add", {
location: location
})
.done(function (data) {
$("#locationsHolder").html(data);
});
});
});
function reversegeocode(callback) {
var lat = $('#lattitude').val();
var lng = $('#longitude').val();
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({
'latLng': latlng
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) { //http://stackoverflow.com/questions/8082405/parsing-address-components-in-google-maps-upon-autocomplete-select
var address_components = results[0].address_components;
var components = {};
jQuery.each(address_components, function (k, v1) {
jQuery.each(v1.types, function (k2, v2) {
components[v2] = v1.long_name
});
})
var output = '';
var needAcomma = false;
if (components.route != undefined) {
output += components.route;
needAcomma = true;
}
if (components.locality != undefined) {
if (needAcomma) {
output += ', ';
}
output += components.locality;
needAcomma = true;
}
if (components.administrative_area_level_1 != undefined) {
if (needAcomma) {
output += ', ';
}
output += components.administrative_area_level_1;
needAcomma = true;
} else if (components.administrative_area_level_2 != undefined) {
if (needAcomma) {
output += ', ';
}
output += components.administrative_area_level_2;
needAcomma = true;
} else if (components.administrative_area_level_3 != undefined) {
if (needAcomma) {
output += ', ';
}
output += components.administrative_area_level_3;
needAcomma = true;
}
$("#location").val(output);
//call the callback
callback(output);
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
}
Change reversegeocode to take a callback parameter (also known as a continuation).
Encapsulate all the stuff that needs to wait for reversegeocode to finish, putting it into an in-place, nameless function.
(Note the similarity to what you're already doing for the click handler.)
With this approach you are also free to add parameters to the callback, which you can use to pass data directly through.
$('.addButton').click(function() {
reversegeocode(function(some_data) {
var location = $("#location").val();//the value I need
//...stuff...
});
});
function reversegeocode(callback){
//...stuff...
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//...stuff...
} else {
alert('Geocoder failed due to: ' + status);
}
callback(some_data);
});
}
You need to use a callback function in the reversegeocode function.
The same exact way as you do ajax :)
$('.addButton').click(function() {
reversegeocode().done(function(location) {
$.post("<?php echo $this->webroot;?>locations/add", {location:location})
.done(function (data) {
$("#locationsHolder").html(data);
});
});
})
To do this you will have reversegeocode return a jquery deferred promise
function reversegeocode() {
return $.Deferred(function(d) {
//do stuff and when it succeeds
d.resolve(location);
//or if it fails
d.reject("something went wrong");
}).promise();
}
I have some issue with the callback inside geocoder.geocode.
var tri = new Array();
for (var j = 1; j < taille; j++) {
where = getBoutique[j].adresse + ", " + getBoutique[j].ville;
boutiqueProche(lat, lon, where, function (distanceO) {
//window.localStorage.setItem("distance", distance);
console.log(distanceO);
tri.push(distanceO);
//return distance;
//console.log("Nous somme dans "+localStorage.getItem("distance"));
});
console.log("Inside " + tri);
}
function boutiqueProche(cLat, cLong, where, callback) {
var geocoder = new google.maps.Geocoder();
var currentPosition = new google.maps.LatLng(cLat, cLong); // On récupère nos info
var recup = getBoutique.length;
var distance;
geocoder.geocode({
'address': where
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var laBoutique = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng());
distance = google.maps.geometry.spherical.computeDistanceBetween(currentPosition, laBoutique);
recup = distance / 1000;
callback(recup);
} else {
if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
setTimeout(function () {
boutiqueProche(cLat, cLong, where, callback); // rappel fonction avec meme param
}, 200);
} else { /*Faire quelque chose */ }
}
});
}
I want to fill the array tri with the data from recup variable. But when I fill tri, nothing happens. It is empty.
What is the problem?