Display google map directions when page load - angularjs

At the moment i have an ionic app, and with angular i created a map that give directions from current user location to a predefined address, if user press "get directions". I will like to display the directions when page load without having to press that button.
This is the controller:
.controller('ContactCtrl', function ($scope, $ionicPlatform, uiGmapGoogleMapApi, $ionicPopup, $cordovaGeolocation) {
// uiGmapGoogleMapApi is a promise.
// The "then" callback function provides the google.maps object.
uiGmapGoogleMapApi.then(function (maps) {
var myLatlng = new google.maps.LatLng(51.51139, -0.2237284);
var mapOptions = {
center: myLatlng,
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// directions object -- with defaults
$scope.directions = {
origin: "",
destination: "12 High Street Kensington",
showList: false
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
// instantiate google map objects for directions
var directionsDisplay = new google.maps.DirectionsRenderer();
var directionsService = new google.maps.DirectionsService();
var geocoder = new google.maps.Geocoder();
var posOptions = {timeout: 10000, enableHighAccuracy: false};
$ionicPlatform.ready(function () {
$cordovaGeolocation
.getCurrentPosition(posOptions)
.then(function (pos) {
map.setCenter((51.498265, -0.313515));
var myLocation = new google.maps.Marker({
position: new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude),
map: map
});
geocoder.geocode({
latLng: new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude)
}, function (responses) {
if (responses && responses.length > 0) {
$scope.directions.origin = responses[0].formatted_address;
} else {
var alertPopup = $ionicPopup.alert({
title: 'Cannot determine address at this location!',
template: 'Please try again!'
});
alertPopup.then(function (res) {
console.log('Cannot determine address at this location!');
});
}
});
}, function (err) {
$ionicPopup.alert({
title: 'Unable to find your location!',
template: 'Please try again!'
});
});
});
$scope.map = map;
// get directions using google maps api
$scope.getDirections = function () {
var request = {
origin: $scope.directions.origin,
destination: $scope.directions.destination,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
directionsDisplay.setMap($scope.map);
directionsDisplay.setPanel(document.getElementById('directionsList'));
$scope.directions.showList = true;
} else {
var alertPopup = $ionicPopup.alert({
title: 'Cannot find address at this location!',
template: 'Please try again!'
});
alertPopup.then(function (res) {
console.log('Google route unsuccesful! Please try again!');
});
}
});
}
});
})
<div class="panel-body">
<div id='map' data-tap-disabled="true">
</div>
<div class="list">
<label class="item item-input item-stacked-label">
<span class="input-label">Origin Address (A)</span>
<input type="text" id="origin" placeholder="Origin address" ng-model="directions.origin"/>
</label>
<label class="item item-input item-stacked-label">
<span class="input-label">Destination Address (B)</span>
<input type="text" id="destination" placeholder="Destination address" ng-model="directions.destination"/>
</label>
</div>
<div class="pad10">
<button class="button button-block button-assertive" ng-click="getDirections()">Get Directions</button>
</div>
<div id="directionsList" ng-show="directions.showList" class="pad10"></div>
</div>
UPDATE
When i try your code i get the following message in console:
getCurrentPosition() and watchPosition() are deprecated on insecure origins, and support will be removed in the future. You should consider switching your application to a secure origin, such as HTTPS. See https://goo.gl/rStTGz for more details.
ionic.bundle.js:20306 TypeError: map.setCenter is not a function
at $cordovaGeolocation.getCurrentPosition.then.$ionicPopup.alert.title (controllers.js:306)
at processQueue (ionic.bundle.js:21888)
at ionic.bundle.js:21904
at Scope.$eval (ionic.bundle.js:23100)
at Scope.$digest (ionic.bundle.js:22916)
at ionic.bundle.js:23139
at completeOutstandingRequest (ionic.bundle.js:13604)
at ionic.bundle.js:13984(anonymous function) # ionic.bundle.js:20306
services.js:65 user Id = c621662e-7389-4c4f-9677-35c1e126f6be
2controllers.js:356 Google route unsuccesful! Please try again!

maybe call getDirection in your init promise?
.controller('ContactCtrl', function ($scope, $ionicPlatform, uiGmapGoogleMapApi, $ionicPopup, $cordovaGeolocation) {
// uiGmapGoogleMapApi is a promise.
// The "then" callback function provides the google.maps object.
uiGmapGoogleMapApi.then(function (maps) {
var myLatlng = new google.maps.LatLng(51.51139, -0.2237284);
var mapOptions = {
center: myLatlng,
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// directions object -- with defaults
$scope.directions = {
origin: "",
destination: "12 High Street Kensington",
showList: false
};
$scope.map = new google.maps.Map(document.getElementById("map"), mapOptions);
// instantiate google map objects for directions
var directionsDisplay = new google.maps.DirectionsRenderer();
var directionsService = new google.maps.DirectionsService();
var geocoder = new google.maps.Geocoder();
var posOptions = {timeout: 10000, enableHighAccuracy: false};
$ionicPlatform.ready(function () {
$cordovaGeolocation
.getCurrentPosition(posOptions)
.then(function (pos) {
$scope.map.setCenter((51.498265, -0.313515));
var myLocation = new google.maps.Marker({
position: new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude),
map: $scope.map
});
geocoder.geocode({
latLng: new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude)
}, function (responses) {
if (responses && responses.length > 0) {
$scope.directions.origin = responses[0].formatted_address;
} else {
var alertPopup = $ionicPopup.alert({
title: 'Cannot determine address at this location!',
template: 'Please try again!'
});
alertPopup.then(function (res) {
console.log('Cannot determine address at this location!');
});
}
});
$scope.getDirections();
}, function (err) {
$ionicPopup.alert({
title: 'Unable to find your location!',
template: 'Please try again!'
});
});
});
// get directions using google maps api
$scope.getDirections = function () {
var request = {
origin: $scope.directions.origin,
destination: $scope.directions.destination,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
directionsDisplay.setMap($scope.map);
directionsDisplay.setPanel(document.getElementById('directionsList'));
$scope.directions.showList = true;
} else {
var alertPopup = $ionicPopup.alert({
title: 'Cannot find address at this location!',
template: 'Please try again!'
});
alertPopup.then(function (res) {
console.log('Google route unsuccesful! Please try again!');
});
}
});
}
});
})

Related

Angular leaflet - Showing multiple marker issue

I am using the following code to add markers in leaflet:
.controller('MapController',
[ '$scope',
'$cordovaGeolocation',
'$stateParams',
'$ionicModal',
'$ionicPopup',
'$http',
function(
$scope,
$cordovaGeolocation,
$stateParams,
$ionicModal,
$ionicPopup,
$http
) {
$scope.$on("$stateChangeSuccess", function() {
$scope.map = {
defaults: {
tileLayer: 'http://{s}.tile.osm.org/{z}/{x}/{y}.png',
maxZoom: 18,
zoomControlPosition: 'bottomleft'
},
markers : {},
events: {
map: {
enable: ['context'],
logic: 'emit'
}
}
};
$scope.locate();
});
$scope.locate = function(){
$scope.map.center = {
lat : location.lat,
lng : location.lng,
zoom : 12,
};
var Location = function() {
if ( !(this instanceof Location) ) return new Location();
this.lat = "";
this.lng = "";
this.name = "";
};
$ionicModal.fromTemplateUrl('templates/addLocation.html', {
scope: $scope,
animation: 'slide-in-up'
}).then(function(modal) {
$scope.modal = modal;
});
$scope.map.markers.push=({
lat:35.654,
lng:73.244,
message:'demo 1'
})
$scope.map.markers.push=({
lat:38.654,
lng:73.244,
message:'demo 2'
})
$scope.$on('leafletDirectiveMap.click', function(event, locationEvent){
$scope.newLocation = new Location();
$scope.newLocation.lat = locationEvent.leafletEvent.latlng.lat;
$scope.newLocation.lng = locationEvent.leafletEvent.latlng.lng;
$scope.modal.show();
});
$scope.saveLocation = function(lat, lang) {
//LocationsService.savedLocations.push($scope.newLocation);
//alert(lat + " - " + lang);
var link = 'http://192.168.5.110/server/addLocation.php';
var json1 = {l1 : lat, l2 : lang , l3: sessionStorage.getItem('loggedin_phone')};
$http.post(link, { data: json1 })
.then(function (res){
$scope.response = res.data.result;
if($scope.response.created=="1"){
$scope.title="Thank You";
$scope.template="Mobile Toilet Added!";
//no back option
/*
$ionicHistory.nextViewOptions({
disableAnimate: true,
disableBack: true
});
$state.go('login', {}, {location: "replace", reload: true});
*/
}else if($scope.response.exists=="1"){
$scope.title="Duplication";
$scope.template="This Location is already added!";
}else{
$scope.title="Failed";
$scope.template="Contact Our Technical Team";
}
var alertPopup = $ionicPopup.alert({
title: $scope.title,
template: $scope.template
});
});
$scope.modal.hide();
};
$cordovaGeolocation
.getCurrentPosition()
.then(function (position) {
$scope.map.center.lat = position.coords.latitude;
$scope.map.center.lng = position.coords.longitude;
$scope.map.center.zoom = 18;
$scope.map.markers.now = {
lat:position.coords.latitude,
lng:position.coords.longitude,
focus: true,
draggable: false,
//message: ''
};
}, function(err) {
// error
console.log("Location error!");
console.log(err);
});
};
}]);
But only the demo2 marker is displaying.
Is there a way to show multiple markers on the leaflet map by using JSON data of latitudes and longitudes loaded from API?
<leaflet defaults="defaults" event-broadcast="events" lf-center="center" markers="markers" layers="layers" id="global-map" width="100%" height="240px"></leaflet>
<leaflet defaults="defaults2" event-broadcast="events2" lf-center="center2" markers="markers2" layers="layers2" id="global-map2" width="100%" height="240px"></leaflet>

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

Geo Location - Using Ionic Framework, AngularJS and Google API

We are trying to using this Codepen within our latest Ionic Framework/AngularJS project and can't seem to figure this issue out.
We want to be able to click 'Find Us' and have the Google Map Marker display our current location.
If anyone can see where we're going wrong please let us know.
Thank you.
// Google Map
.controller('MapCtrl', function($scope, $ionicLoading, $compile) {
function initialise() {
var myLatlng = new google.maps.LatLng(53.068165,-4.076803);
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;
}
google.maps.event.addDomListener(window, 'load', initialise);
$scope.centerOnMe = function() {
if(!$scope.map) {
return;
}
$scope.loading = $ionicLoading.show({
showBackdrop: true
});
navigator.geolocation.getCurrentPosition(function(pos) {
$scope.map.setCenter(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
$scope.loading.hide();
},
function(error) {
alert('Unable to get location: ' + error.message);
});
};
});
Here's a good example of this.
Codepen link
.controller('MarkerRemoveCtrl', function($scope, $ionicLoading) {
$scope.positions = [{
lat: 43.07493,
lng: -89.381388
}];
$scope.$on('mapInitialized', function(event, map) {
$scope.map = map;
});
$scope.centerOnMe= function(){
$ionicLoading.show({
template: 'Loading...'
});
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
$scope.positions.push({lat: pos.k,lng: pos.B});
console.log(pos);
$scope.map.setCenter(pos);
$ionicLoading.hide();
});
};
});
I did use a directive for google maps, just to keep everything in angular-land.
Here is a CodePen of an Ionic app with Google Maps
angular.module('ionic.example', ['ionic'])
.controller('MapCtrl', function($scope, $ionicLoading, $compile) {
function initialize() {
var myLatlng = new google.maps.LatLng(43.07493,-89.381388);
var mapOptions = {
center: myLatlng,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"),
mapOptions);
//Marker + infowindow + angularjs compiled ng-click
var contentString = "<div><a ng-click='clickTest()'>Click me!</a></div>";
var compiled = $compile(contentString)($scope);
var infowindow = new google.maps.InfoWindow({
content: compiled[0]
});
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Uluru (Ayers Rock)'
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
$scope.map = map;
}
google.maps.event.addDomListener(window, 'load', initialize);
$scope.centerOnMe = function() {
if(!$scope.map) {
return;
}
$scope.loading = $ionicLoading.show({
content: 'Getting current location...',
showBackdrop: false
});
navigator.geolocation.getCurrentPosition(function(pos) {
$scope.map.setCenter(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
$scope.loading.hide();
}, function(error) {
alert('Unable to get location: ' + error.message);
});
};
$scope.clickTest = function() {
alert('Example of infowindow with ng-click')
};
});
when you find the current location of your phone first you find out the latitude and longitude.So First,Add the plugin your project
1.cordova plugin add cordova-plugin-geolocation
2.module.controller('GeoCtrl', function($cordovaGeolocation,$http) {
var posOptions = {timeout: 10000, enableHighAccuracy: false};
$cordovaGeolocation
.getCurrentPosition(posOptions)
.then(function (position) {
var lat = position.coords.latitude //here you get latitude
var long = position.coords.longitude //here you get the longitude
$http.get('http://maps.googleapis.com/maps/api/geocode/json?latlng='+lat+','+long+'&sensor=true').then(function(data){ $rootScope.CurrentLocation=data.data.results[0].formatted_address;//you get the current location here
}, function(err) {
// error
});
}, function(err) {
// error
});
}):

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