This was suppose to be simple, I've used show/hide plenty of times...
2 hours later nothing... works on brower... it doesn't work on the mobile andriod device I'm testing on.
<li class="item" style="text-align:center" ng-if="showBlist==0">
No bouncr's available
</li>
<li class="item" ng-repeat="data in bouncrList" ng-if="showBlist==1">
<a class="item item-avatar" href="#">
<img src="{{avatar}}">
<h2>{{data.name}}</h2>
<p>{{data.venue}}, {{data.address}}</p>
</a>
</li>
$ionicPlatform.ready(function() {
$scope.initMap = function() {
$scope.positions = [];
$ionicLoading.show({
template: 'Loading...'
});
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map = new google.maps.Map(document.getElementById('map'), {
center: pos,
zoom: 12
});
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: pos,
radius: 5000,
type: ['night_club'],
}, callback);
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
var locale = JSON.stringify(results[0].vicinity);
bouncrFactory.bouncrs(locale).then(function(data){
$scope.bouncrList = data.data.bouncrs
$rootScope.showBlist = data.data.showBlist
})
$rootScope.$apply()
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
console.log(place.name)
});
}
$ionicLoading.hide();
})
}
$scope.initMap()
});
$ionicPlatform.ready was added from another solution
$scope.apply was added from another solution
i've used
$timeout(function(){
...
},1000)
and every other solution i can find
Related
I have an app that I need that open an infowindow on a google map, to just show it for 1 second when I do click on the panel in the side bar. After this, it need not work anymore.
I have a list of the markers and information in the sidebar, when the user make a click in a some of these markers I need that the infowindow to be open.
(function(){
angular.module('mapCtrl', ['presentacionService'])
.controller('MapController', function($scope, Presentacion) {
var self = this;
function initialize() {
var options = {
googleApiKey: '',
locationColumn: 'geometry',
map_center: [-16.494898, -68.133553],
locationScope: 'La Paz'
};
options = options || {};
self.googleApiKey = options.googleApiKey || "";
self.locationColumn = options.locationColumn || "geometry";
self.locationScope = options.locationScope || "";
self.defaultZoom = options.defaultZoom || 10;
self.map_centroid = new google.maps.LatLng(options.map_center[0], options.map_center[1]);
self.myOptions = {
zoom: self.defaultZoom,
center: self.map_centroid,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
self.map = new google.maps.Map($("#map")[0], self.myOptions);
var infoWindow = new google.maps.InfoWindow();
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
$scope.markers = [];
var createMarker = function (info){
var marker = new google.maps.Marker({
map: self.map,
position: new google.maps.LatLng(info.latitud, info.long),
title: info.nombre,
date: info.date,
imagen: info.imagen,
nombre_categoria: info.nombre_categoria
});
marker.content = '<div class="infoWindowContent">' + info.descripcion + '</div>';
google.maps.event.addListener(marker, 'click', function(){
infoWindow.setContent('<h2>' + marker.title + '</h2>' + marker.content);
infoWindow.open(self.map, marker);
});
$scope.markers.push(marker);
};
Presentacion.getAll().success(function (datos) {
for (var i = 0; i < datos.length; i++){
createMarker(datos[i]);
}
});
$scope.openInfoWindow = function(e, selectedMarker){
console.log('show something');
e.preventDefault();
new google.maps.event.trigger(selectedMarker, 'click' );
};
}
google.maps.event.addDomListener(window, 'load', initialize);
});
})();
an in the view:
<div class="row list_special" ng-repeat="marker in markers | orderBy : 'date'">
<div class="panel-google-plus" ng-click="openInfoWindow($event, marker)">
</div>
</div>
I prepared a Plunker to simulate functionalities desired for your project.
Here is the url: http://plnkr.co/edit/gIhNLQgfiiD4QfuQQOi4?p=preview
I have substituted your service Presentacion with a simple array places initialized in the MainCtrl (and also the markers is a property of MainCtrl scope but inherited by MapController):
$scope.markers = [];
$scope.places = [];
$scope.places.push({lat: 44.99758207, lng: 7.140598296999997, ...);
No other editing in your code and it is working as required: you can click on an item and it will open infowindow all the times you want.
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
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!');
});
}
});
}
});
})
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
I have a map built on angular. https://vineyardcincinnati.com/nigeria-map
I have a field updating based on the google marker clicked. Is there a way to initialize an angular object based on the page load? The content box is currently blank until the user sends JSON data based on a click event.
Here is my angular code:
$scope.map = new google.maps.Map(document.getElementById('map'), mapOptions);
$scope.markers = [];
var infoWindow = new google.maps.InfoWindow({
maxWidth: 200
});
var createMarker = function (info){
var marker = new google.maps.Marker({
map: $scope.map,
position: new google.maps.LatLng(info.lat, info.long),
title: info.location,
image: info.img,
date: info.date,
quote: info.quote
});
marker.content = '<div class="infoWindowContent">' + info.desc + '</div>';
google.maps.event.addListener(marker, 'click', function(){
infoWindow.setContent(marker.content);
$scope.selectedMarker = marker;
$scope.$apply();
infoWindow.open($scope.map, marker);
});
$scope.markers.push(marker);
}
for (i = 0; i < cities.length; i++){
createMarker(cities[i]);
}
$scope.openInfoWindow = function(e, selectedMarker){
e.preventDefault();
google.maps.event.trigger(selectedMarker, 'click');
}
});
Here is my view
<div id="containter" ng-app="mapsApp" ng-controller="MapCtrl">
<div id="map"></div>
<div id="class">
<h1> {{selectedMarker.title}}</h1>
<p>{{selectedMarker.quote}}</p>
<p>Completed {{selectedMarker.date}}</p>
</div>
</div>
Use $timeout from inside your directive's controller:
$timeout(function() {
// initialize plugin on load here...
});
You can use module.run.
angular.module('myModule',[])
.run(function($rootScope){
$rootScope.selected = "foo";
// code runs on module init
}