Reverse Geocoding AngularJS - angularjs

I have to improve my code with reverse geocoding. Now my app get the position by device's GPS.
This is my controller:
.controller('MapCtrl', function($scope, $ionicLoading, $compile) {
function initialise() {
function onSuccess(position){
var myLatlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var mapOptions = {
zoom: 15,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
});
$scope.map = map;
}
function onError(error){
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
google.maps.event.addDomListener(window, 'load', initialise);
});
I found in this link a solution, but I'm not be able to integrate it with my code.
Anyone can help me?

This is the function to get address from lat and long.
$scope.geocoder.geocode({ 'latLng': $scope.latlng }, function (results, status)
And you need to include google api's:
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&ver=2014-07-18"></script>
After this you must handle the response.
I post some example code.
$scope.geocoder.geocode({ 'latLng': $scope.latlng }, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
if (results[1]) {
$scope.address = results[1].address_components;
$scope.gps_data.address = $scope.address;
//your code here
// some example results parsing code
var i;
$scope.comune = undefined;
for (i = 0; i < $scope.gps_data.address.length; i += 1) {
if ($scope.gps_data.address[i].types.indexOf("administrative_area_level_3") > -1) {
$scope.comune = $scope.gps_data.address[i].short_name;
console.log($scope.comune);
}
}
if ($scope.comune === undefined) {
for (i = 0; i < $scope.gps_data.address.length; i += 1) {
if ($scope.gps_data.address[i].types.indexOf("locality") > -1) {
$scope.comune = $scope.gps_data.address[i].short_name;
}
}
}
} else {
console.log('Location not found');
$scope.firstExecution = false;
}
} else {
console.log('Geocoder failed due to: ' + status);
$scope.firstExecution = false;
}
});
Anyway, you need to check this documentation for better knwoledgment
https://developers.google.com/maps/documentation/javascript/examples/geocoding-reverse
Here you can find all the tags about the object structure that you recieve from google's api.

Related

Only getting a few markers in the map

I am very new to angularJS and still exploring.I have created a map and showing around 1500 markers in it but when I load only 11 markers are visible.I am taking the Zip codes from a XML file and using geocoding I am converting them to LatLng and showing in map.Can any one suggest any solution.
Thanks in advance.
//Angular App Module and Controller
var mapApp = angular.module('mapApp', []);
// app.directive("importSheetJs", [SheetJSImportDirective]);
mapApp.factory('mySHaredService', function ($rootScope) {
var mySHaredService = {};
mySHaredService.message = '';
mySHaredService.prepForBroadcast = function (msg) {
this.message = msg;
this.broadcastItem();
};
return mySHaredService;
});
mapApp.controller('MapController', function ($scope, $timeout, $window, $rootScope, mySHaredService) {
//Parsing data from XML
$rootScope.zipArray = [];
var url = "location.xlsx";
var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
oReq.responseType = "arraybuffer";
$rootScope.LatLongList = [{
"latitudeValue": "",
"longitudeValue": ""
}];
oReq.onload = function (e) {
var arraybuffer = oReq.response;
var data = new Uint8Array(arraybuffer);
var arr = new Array();
for (var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
var bstr = arr.join("");
var workbook = XLSX.read(bstr, { type: "binary" });
var first_sheet_name = workbook.SheetNames[0];
var address_of_cell = "K1";
var worksheet = workbook.Sheets[first_sheet_name];
data = JSON.stringify(XLSX.utils.sheet_to_json(worksheet));
console.log("Messege data" + data);
var finalData = JSON.parse(data);
for (var i = 0; i <= finalData.length; i++) {
// console.log("Zip code is " + finalData[i].Zip);
$rootScope.zipArray.push(finalData[i].ZIP);
console.log("Zip code inside zip array is " + $rootScope.zipArray[i]);
}
}
setTimeout(function () {
$scope.$apply(function () {
})
}, 17770);
$timeout(function() {
console.log("Zip data from excel sheet" + $rootScope.zipArray)
var geocoder = new google.maps.Geocoder();
for (var i = 15; i <= $rootScope.zipArray.length; i++) {
var address = $rootScope.zipArray[i];
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
$rootScope.LatLongList.push({
"latitudeValue": latitude,
"longitudeValue": longitude
});
}
});
}
// setTimeout(function () {
// $scope.$apply(function () {
// })
// }, 30000);
$timeout(function () {
console.log("Latitude value " + $rootScope.LatLongList[1].latitudeValue)
var mapOptions = {
zoom: 11,
center: new google.maps.LatLng(33.6496252, -117.9190418),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
$scope.map = new google.maps.Map(document.getElementById('map'), mapOptions);
var circle = new google.maps.Circle({
center: new google.maps.LatLng(33.6496252, -117.9190418),
map: $scope.map,
radius: 10000, // IN METERS.
fillColor: '#FF6600',
fillOpacity: 0.3,
strokeColor: "#FFF",
strokeWeight: 0 // DON'T SHOW CIRCLE BORDER.
});
var bounds = circle.getBounds();
$scope.markers = [];
$rootScope.selectedAd = "";
var selectedLocation = [{ "lat": 0, "long": 0 }];
var infoWindow = new google.maps.InfoWindow();
var createMarker = function (info) {
var marker = new google.maps.Marker({
map: $scope.map,
position: new google.maps.LatLng(info.latitudeValue, info.longitudeValue),
title: ""
});
marker.content = '<div class="infoWindowContent">' + '<br />' + info.latitudeValue + ' E,' + info.longitudeValue + ' N, </div>';
google.maps.event.addListener(marker, 'click', function () {
infoWindow.setContent('<h2>' + marker.title + '</h2>' +
marker.content);
infoWindow.open($scope.map, marker);
selectedLocation[0].lat = marker.getPosition().lat();
selectedLocation[0].long = marker.getPosition().lng();
console.log("Latitude is " + selectedLocation[0].lat + "Longitude is " + selectedLocation[0].long);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
latLng: marker.getPosition()
}, $scope.selectedLoc = function (responses) {
if (responses && responses.length > 0) {
// alert(responses[0].formatted_address);
$rootScope.selectedAd = responses[0].formatted_address;
setTimeout(function () {
$scope.$apply(function () {
$rootScope.selectedAd = responses[0].formatted_address;
})
}, 1000);
$timeout(function () {
$rootScope.selectedAd = responses[0].formatted_address;
$scope.handleClick = function (msg) {
mySHaredService.prepForBroadcast($rootScope.selectedAd);
}
$scope.$on('handleBroadcast', function () {
$scope.message = $rootScope.selectedAd;
})
}, 2000);
} else {
}
});
});
$scope.markers.push(marker);
}
setTimeout(function () {
}, 3000);
$timeout(function () {
for (i = 1; i < $rootScope.LatLongList.length; i++) {
console.log(bounds.contains(new google.maps.LatLng($rootScope.LatLongList[i].latitudeValue, $rootScope.LatLongList[i].longitudeValue)));
// if (bounds.contains(new google.maps.LatLng($rootScope.LatLongList[i].latitudeValue, $rootScope.LatLongList[i].longitudeValue))) {
createMarker($rootScope.LatLongList[i]);
console.log("The value of i is " + i);
// }
}
}, 4000);
$scope.openInfoWindow = function (e, selectedMarker) {
var data = $rootScope.selectedAd
this.broadcastItem();
window.location = "valuePage.html";
}
}, 4000);
}, 2000);
oReq.send();
});
mapApp.controller("viewApp", function ($scope, $rootScope, mySHaredService, $timeout) {
// $scope.selectedAd = Products.FirstName;
// $scope.selectedAd = Products.FirstName;
setTimeout(function () {
$scope.$on('handleBroadcast', function () {
$scope.message = mySHaredService.message;
});
}, 3000);
$timeout(function () {
$scope.$on('handleBroadcast', function () {
$scope.message = mySHaredService.message;
});
}, 4000);
});
This is because you are sending too many requests through per second.
In addition to daily quota limits, the geocoding service is rate limited to 50 QPS (queries per second), calculated as the sum of client-side and server-side queries.
The Optimizing Quota Usage When Geocoding has a lot of strategies on how to account for that.
In your case I suggest doing a randomized interval for each request you make that way they are spread out you avoid going over the 50 request per second limit.
I've modified the part of your code sample where you are making the request.
mapApp.controller('MapController', function ($scope, $timeout, $window, $rootScope, mySHaredService) {
//Parsing data from XML
$rootScope.zipArray = [];
var url = "location.xlsx";
var randomTime = Math.round(Math.random()*(3000-500))+500;
var geocodeRequest = setTimeout(function() {
var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
oReq.responseType = "arraybuffer";
$rootScope.LatLongList = [{
"latitudeValue": "",
"longitudeValue": ""
}];
oReq.onload = function (e) {
var arraybuffer = oReq.response;
var data = new Uint8Array(arraybuffer);
var arr = new Array();
for (var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
var bstr = arr.join("");
var workbook = XLSX.read(bstr, { type: "binary" });
var first_sheet_name = workbook.SheetNames[0];
var address_of_cell = "K1";
var worksheet = workbook.Sheets[first_sheet_name];
data = JSON.stringify(XLSX.utils.sheet_to_json(worksheet));
console.log("Messege data" + data);
var finalData = JSON.parse(data);
for (var i = 0; i <= finalData.length; i++) {
// console.log("Zip code is " + finalData[i].Zip);
$rootScope.zipArray.push(finalData[i].ZIP);
console.log("Zip code inside zip array is " + $rootScope.zipArray[i]);
}
}
setTimeout(function () {
$scope.$apply(function () {
})
}, 17770);
}, randomTime);

How to merge two different object from JSON data

Hi I need some help with this code snippet. The output that I get is multiple different objects of JSON data. But I want to extract the destination data then merge them as an array. But all the data I get is only one data merge as an array, one by one.
Here is the output:
$scope.findHospital = function(){
$ionicLoading.show({
template: '<ion-spinner icon="bubbles"></ion-spinner><br/>Acquiring location!'
});
var posOptions = {
enableHighAccuracy: true,
timeout: 20000,
maximumAge: 0
};
$cordovaGeolocation.getCurrentPosition(posOptions).then(function (position) {
var lat = position.coords.latitude;
var long = position.coords.longitude;
var infowindow;
var myLatlng = new google.maps.LatLng(lat, long);
var mapOptions = {
center: myLatlng,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: myLatlng,
radius: 5000,
type: ['police']
}, callback);
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(lat, long);
geocoder.geocode({'latLng': latlng}, function(results, status) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
var request = { reference: place.reference };
service.getDetails(request, function(details, status) {
console.log(details);
var url = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins="+results[0].formatted_address+"&destinations="+details.formatted_address+"&key=AIzaSyDDxMGpu5SP5XwZGrKw5BQWl_r2dgLgpPY";
var distances = [];
$http.get(url).then(function(response){
var str = response.data.rows[0].elements[0].distance.text;
distances = distances.concat(str);
console.log(distances);
});
}
});
}
}
}
CODE UPDATED!
I strongly suspect, distances array is initializing everytime when createMarker method is called. So, put your distances in global scope. i.e. just above your resolving getCurrentPosition promise.
var distances = [];
$cordovaGeolocation.getCurrentPosition(posOptions).then(function (position) {
// your code
and remove distances intialization from inner code.
This is what you need!! A array outside of your function createMarker. When you call $http.get, you should concatenate the response with your distances array.
var distances = []; // HERE
function createMarker(place) {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(lat, long);
geocoder.geocode({'latLng': latlng}, function(results, status) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
var request = { reference: place.reference };
service.getDetails(request, function(details, status) {
var url = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins="+results[0].formatted_address+"&destinations="+details.formatted_address+"&key=AIzaSyDDxMGpu5SP5XwZGrKw5BQWl_r2dgLgpPY";
$http.get(url).then(function(response){
var str = response.data.rows[0].elements[0].distance.text;
distances = distances.concat(str); // HERE
});
}
});
}

Incorrect marker location

I am Using the $http Service in Ionic to dynamically load Google Map Markers, and I use this method:
google.maps.Geocode
To give a lat and lang, but this code is throwing some error.
facebookExample.controller('carteController', function ($scope, $ionicLoading, $location, $cordovaGeolocation, $compile, $http) {
$scope.back = function () {
$location.path("/accueil");
}
$scope.init = function () {
$http.get('http://#ip:8080/elodieService/categories/', {
params: {
fields: "nomcategorie,typecategorie",
format: "json"
}
}).then(function (result) {
console.log("SUCCESS!" + result.data);
console.log(JSON.stringify(result));
$scope.categorieData = result.data;
});
var options = {timeout: 10000, enableHighAccuracy: true};
$cordovaGeolocation.getCurrentPosition(options).then(function (position) {
var latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var mapOptions = {
center: latLng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
$scope.map = new google.maps.Map(document.getElementById("map"), mapOptions);
google.maps.event.addListenerOnce($scope.map, 'idle', function () {
var marker = new google.maps.Marker({
map: $scope.map,
animation: google.maps.Animation.DROP,
position: latLng
});
$http.get('http://#ip/elodieService/evenements/', {
params: {
fields: "adresse",
format: "json"
}
}).then(function (result) {
console.log("SUCCESS!" + result.data);
console.log(JSON.stringify(result));
$scope.adresseData = result.data;
console.log("result.data: ", result.data.adresse);
var records = result.data;
for (var i = 0; i < records.length; i++) {
var record = records[i];
var adresse = record.adresse;
console.log("adresse obtenu par web service");
console.log(adresse);
var resultat = "";
geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': adresse}, callback);
function callback(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log("results[0].geometry.location");
console.log(results[0].geometry.location.latitude);
lat = results[0].geometry.location.lat();
console.log("lat");
console.log(lat);
lng = results[0].geometry.location.lng();
console.log("lng");
console.log(lng);
console.log(JSON.stringify(results));
var markerPos = new google.maps.LatLng(lat[i], lng[i]);
var marker = new google.maps.Marker({
map: $scope.map,
animation: google.maps.Animation.DROP,
position: markerPos
});
} else {
console.log(status);
}
}
}
});
var infoWindow = new google.maps.InfoWindow({
content: "Here I am!"
});
google.maps.event.addListener(marker, 'click', function () {
infoWindow.open($scope.map, marker);
});
console.log(status);
}, function (error) {
console.log("Could not get location");
});
});
}
});
carte.html
<ion-view title="Carte" ng-init="init()">
<ion-content>
<div id="map" data-tap-disabled="true"></div>
</ion-content>
</ion-view>
Error:
incorrect marker location
How can I fix it?
You are passing the incorrect value to LatLng class as lat[i], lng[i]. The index position [i] is invalid.
So change your code like this:
lat = results[0].geometry.location.lat();
console.log("lat");
console.log(lat);
lng = results[0].geometry.location.lng();
console.log("lng");
console.log(lng);
console.log(JSON.stringify(results));
var markerPos = new google.maps.LatLng(lat, lng); // << Fix it here
Even, you don't have to define those lat and lng because you are getting it from a LatLng instance.
if (status == google.maps.GeocoderStatus.OK) {
console.log("results[0].geometry.location", results[0].geometry.location, JSON.stringify(results));
// No need to initialize again as the "results[0].geometry.location" is an instance of LatLng class itself
var markerPos = results[0].geometry.location;
var marker = new google.maps.Marker({
map: $scope.map,
animation: google.maps.Animation.DROP,
position: markerPos
});
}
See Geocoding Results:
results[]: {
types[]: string,
formatted_address: string,
address_components[]: {
short_name: string,
long_name: string,
postcode_localities[]: string,
types[]: string
},
partial_match: boolean,
place_id: string,
postcode_localities[]: string,
geometry: {
location: LatLng,
location_type: GeocoderLocationType
viewport: LatLngBounds,
bounds: LatLngBounds
}
}

Markers click events are not working in mobile device

I have created google maps for Nearby food courts. In this markers are displayed in browser and clickable and giving info window data.But same thing coming to mobile, markers are displayed and when am clicking the marker(tap the marker) info window data is not displayed.I tried with so many forums and changes lot of code and debug but i couldn't find the solution.
foodFactory.js
var foodModule = angular.module('foodModule', []);
foodModule.factory("foodFactory", ['$rootScope', '$window','foodServices', 'localStorageService', '$state', '$ionicLoading','$stateParams',
function($rootScope, $window, foodServices, localStorageService, $state, $ionicLoading, $stateParams, $cordovaGeolocation ) {
var foodCourtmap = {};
var marker = {};
var directionsDisplay = new google.maps.DirectionsRenderer({'draggable': true });
var directionsService = new google.maps.DirectionsService();
foodCourtmap.centerOnMe = function() {
initialize();
};
//intialze the google map it's show current location.
function initialize() {
var infowindow = new google.maps.InfoWindow();
navigator.geolocation.getCurrentPosition(function(pos) {
foodCourtmap.latitude = pos.coords.latitude;
foodCourtmap.longitude = pos.coords.longitude;
var site = new google.maps.LatLng( foodCourtmap.latitude, foodCourtmap.longitude);
var currentmapOptions = {
center: site,
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//current location address based on Latitude and Longitude
var lat = parseFloat(foodCourtmap.latitude);
var lng = parseFloat(foodCourtmap.longitude);
var latlng = new google.maps.LatLng(lat, lng);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'latLng': latlng
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
var contentString = "Location: " + results[1].formatted_address;
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: 'Current Location'
});
google.maps.event.addListener(marker, 'click', function(event) {
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
}
}
});
var map = new google.maps.Map(document.getElementById("food_map_canvas"), currentmapOptions);
// Places
var request = {
location:site,
radius: '5000',
name: ['restaurent']
};
var service = new google.maps.places.PlacesService(map);
service.search( request, callback );
function callback(results, status)
{
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
createMarker(results[i]);
}
}
else
{
alert('No results found');
}
}
var image = new google.maps.MarkerImage('img/Restaurant.png');
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
title: place.name+","+place.vicinity,
position: place.geometry.location,
icon:image
});
var contentString = place.name+","+place.vicinity;
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
}
foodCourtmap.map = map;
});
};
$rootScope.createFoodCourt = function() {
foodCourtmap.centerOnMe();
}
return {
init: function() {
foodCourtmap.centerOnMe();
return foodCourtmap;
}
};
}
]);
food.html
<ion-view>
<ion-content scroll="false">
<div id="food_map_canvas" data-tap-disabled="true" style="float:right;width:100%; height:100%"></div>
</ion-content>
</ion-view>
So please anyone help in these regards.
The mousedown event was an improvement, however, on iOS the events still fired intermittently for me. After more investigation I found a solution that works 100% of the time by setting optimized: false when creating the marker in addition to using the mousedown event.
E.g.
var newMarker = new google.maps.Marker({
position: latLong,
map: map,
icon: 'https://maps.google.com/mapfiles/ms/icons/green-dot.png',
optimized: false
});
https://code.google.com/p/gmaps-api-issues/issues/detail?id=3834
I had the same issue. The problem was 'click' event is not triggering when we touch on the mobile screen. So I changed to 'mousedown' event. Now I am able to add markers

angular, try to display object in ng-repeat fails

i'm writing an mobile application in javascript with angularJS and ionicframework (last beta v.11), i create dinamically an object and want to display all objects inside in a ng-repeat. Why nr-repeat don't display anything?
This is screen from my object:
I use this code for put values in scope:
$scope.distanceSuppliers = myCar;
And this is the code in html:
<ion-item ng-repeat="(id, supplier) in distanceSuppliers">
<div class="items item-button-right" ng-click="openDetails(id)">
{{supplier.name}}<br />
{{supplier.address}}<br />
</div>
</ion-item>
This is my complete code for JS:
.controller('suppliers', function($scope, cw_db, $ionicPopup, $ionicActionSheet, appdelegate, $rootScope, $firebase, $location, $ionicLoading, cw_position) {
$ionicLoading.show({
template: 'Updating data..'
});
var geocoder;
var tot = 0;
var done = 0;
geocoder = new google.maps.Geocoder();
cw_db.getData(cw_db.getSuppliers(), "", function(suppliers) {
cw_position.getPosition(function (error, position) {
suppliers.on('value', function(supp) {
$scope.distanceSuppliers = {};
tot = 0;
done = 0;
supp.forEach(function(childSnapshot) {
tot++;
var childData = childSnapshot.val();
if (childData.address) {
calculateDistance(childData, position.coords.latitude, position.coords.longitude);
}
});
});
$ionicLoading.hide();
});
});
function calculateDistance(childData, usrLat, usrLon) {
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [new google.maps.LatLng(usrLat, usrLon)],
destinations: [childData.address],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
done++;
var results = response.rows[0].elements;
childData.distance = results[0].distance.value;
$scope.distanceSuppliers.push(childData);
if (done == tot) {
console.log($scope.distanceSuppliers);
}
}
});
}
$scope.openDetails = function(index) {
//appdelegate.setCallId(index);
//$location.path("/app/supplierDetails");
}
})
what's wrong?
Not sure, but I believe you have a data binding update problem.
Try using the $timeout to force the render:
w_position.getPosition(function (error, position) {
$timeout(function() {
suppliers.on('value', function(supp) {
$scope.distanceSuppliers = {};
tot = 0;
done = 0;
supp.forEach(function(childSnapshot) {
tot++;
var childData = childSnapshot.val();
if (childData.address) {
calculateDistance(childData, position.coords.latitude, position.coords.longitude);
}
});
});
$ionicLoading.hide();
});
});
And don't forget to add the $timeout parameter to the controller:
.controller('suppliers', function($scope, ...<other parameters here>..., $timeout) {
I found the problem! Fix using $scope.$apply();
The problem was that i was writing in a different $scope using this code:
cw_position.getPosition(function (error, position) {
suppliers.on('value', function(supp) {
tot = 0;
done = 0;
supp.forEach(function(childSnapshot) {
tot++;
var childData = childSnapshot.val();
if (childData.address) {
calculateDistance(childData, position.coords.latitude, position.coords.longitude);
}
});
});
$ionicLoading.hide();
});
where cw_position.getPosition call a js with this code:
angular.module('cw_position', [])
.service('cw_position', function() {
this.getPosition = function(callback) {
navigator.geolocation.getCurrentPosition(
function (position) {
return callback(null, position);
},
function(error) {
return callback(error, null);
}
);
}
// Built google maps map option
//
this.getGoogleMapOptions = function (lat, lon, zoom, type) {
if (type == null) {
type = google.maps.MapTypeId.ROADMAP;
}
var mapOptions = {
center: new google.maps.LatLng(lat, lon),
zoom: zoom,
mapTypeId: type
};
return mapOptions;
}
});
navigator.geolocation.getCurrentPosition causes the 'problem'
Thx to all for your help

Resources