Angular js ngclick doesnt work in infowindow - angularjs

I created a map with Google maps. At first the infowindow is open when the init function is called. I select a place from the map $scope.kds is working and the contents of the infowindow change. There is a button in the infowindow. When I click the button doesnt work. How can I do?
window.ngApp = angular.module('test', []);
window.ngApp.controller('controllerMap', ['$scope', '$location', '$compile', function ($scope, $location, $compile) {
$scope.init = function () {
$scope.latlng = new google.maps.LatLng($scope.lat, $scope.lng);
$scope.map = new google.maps.Map(document.getElementById('map'), {
center: $scope.latlng,
zoom: $scope.zoom,
minZoom: 6,
maxZoom: 21
});
$scope.marker = new google.maps.Marker({
map: $scope.map,
position: $scope.latlng,
draggable: true,
icon: 'static/img/pin-4ldpi.png'
});
$scope.infowindow = new google.maps.InfoWindow({
content: "",
maxWidth: 175
});
google.maps.event.addListener($scope.map, 'click', function (event) {
$scope.kds ();
});
$scope.kds = function(){
$.ajax({
type: 'post',
url: "/",
dataType: 'json',
async: true,
cache: false,
data: {
mode: "getkds",
lat: data.response.lat,
lng: data.response.lng
},
success: function (data) {
if (data.response) {
$scope.cityName = data.response.cityName;
$scope.contentString = "<div class='text-center fs-16 py-3'>" + $scope.cityName + " <br>\n" +
"<a ng-click='runfunc();' class='fs-12 text-red font-sfprodisplay-600 btn btn-color3 btn-sm mt-3'>Analyses</a></div>";
$scope.infowindow.setContent($scope.contentString);
$scope.infowindow.open($scope.map, $scope.marker);
if (!$scope.$$phase) $scope.$apply();
}
}
});
}
$scope.runfunc=function(){
alert("123");
}
$scope.init();
}]);

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>

ngMaterial error in Angular app: TypeError: Cannot read property 'confirm' of undefined

I am trying to use ngMaterial in my Angular app and getting the errors: ReferenceError: $event is not defined and TypeError: Cannot read property 'confirm' of undefined. I have looked at the ngMaterial docs and am using the code from this example: https://material.angularjs.org/latest/demo/dialog but can't find what I am doing wrong.
The ReferenceError refers to this line:
$timeout($scope.showConfirm($event), 500);
And the TypeError refers to:
var confirm = $mdDialog.confirm()
Below is my code:
html:
<div style="height: 100%">
<h1>TEST</h1> <!--NOT SHOWING ON PAGE WHICH MEANS THIS IS NOT BEING INVOKED WHEN
URL IS: '/getLocation' like it should-->
<ui-gmap-google-map
class="md-primary md-raised" ng-click="showConfirm($event)"
center='map.center'
zoom='map.zoom'
draggable='map.draggable'
dragging='map.dragging'
refresh='map.refresh'
options='map.options'
events='map.events'
pan='map.pan'>
<ui-gmap-marker
idKey='1'
events='map.events'
coords='map.center'
>
</ui-gmap-marker>
</ui-gmap-google-map>
<script src='//maps.googleapis.com/maps/api/js?key=AIzaSyD4_0KuPivZyV-1EwNGmBCgLc_Z0o8Dyw8'></script>
</div>
Controller:
(function (window, ng) {
ng.module('app', ['uiGmapgoogle-maps', 'ui.router', 'ngMaterial'])
.config(function ($stateProvider) { //had: , $stateChangeError included in the function parameters, but that caused error
$stateProvider.state('getLocation', {
url: '/getLocation',
templateUrl: 'getlocation.html',
controller: 'GetlocationCtrl',
});
})
.controller('GetlocationCtrl', ['$scope', "uiGmapLogger", "uiGmapGoogleMapApi", "$state", "$stateParams", "$timeout",
function ($scope, $log, GoogleMapApi, $state, $stateParams, $timeout, $mdDialog) {
$log.currentLevel = $log.LEVELS.debug;
center = { latitude: 49.22, longitude: -122.66 }; //default center
console.log($stateParams);
$scope.map = {
center: center,
pan: false,
zoom: 16,
refresh: false,
events:
{ click: function newCenter(mapModel, eventName, originalEventArgs)
{
$scope.$apply(function(){
var e = originalEventArgs[0];
$scope.map.center = { latitude: e.latLng.lat(), longitude: e.latLng.lng() };
$timeout($scope.showConfirm($event), 500);
});
}
}
}
$scope.map.circle = {
id: 1,
center: center,
radius: 500, //(current time - date lost)*km/hour
stroke: {
color: '#08B21F',
weight: 2,
opacity: 1
},
fill: {
color: '#08B21F',
opacity: 0.5
},
geodesic: false, // optional: defaults to false
draggable: false, // optional: defaults to false
clickable: true, // optional: defaults to true
editable: false, // optional: defaults to false
visible: true, // optional: defaults to true
events: {
dblclick: function () {
$log.debug("circle dblclick");
},
radius_changed: function (gObject) {
var radius = gObject.getRadius();
$log.debug("circle radius radius_changed " + radius);
}
}
};
$scope.showConfirm = function (ev) {
// Appending dialog to document.body to cover sidenav in docs app
var confirm = $mdDialog.confirm()
.title('Would you like to delete your debt?')
.textContent('All of the banks have agreed to forgive you your debts.')
.ariaLabel('Lucky day')
.targetEvent(ev)
.ok('Please do it!')
.cancel('Sounds like a scam');
$mdDialog.show(confirm).then(function() {
$scope.status = 'You decided to get rid of your debt.';
}, function() {
$scope.status = 'You decided to keep your debt.';
});
};
} ]); //end of controller
//THIS LISTENER DOES NOT DO ANYTHING
// $scope.map.event.addListener(map, 'click', function(event) {
// alert(event.latLng); // in event.latLng you have the coordinates of click
//});
//function confirmLocation() {
// alert('Use this location as {{petName}}\'s last location?')
//}
})(window, angular);
Your controller does not have mdDialog injected, and there is a issue in the way you are injecting, change like below,
controller('GetlocationCtrl', ['$scope', "uiGmapLogger", "uiGmapGoogleMapApi", "$state", "$stateParams", "$timeout","$mdDialog",
function ($scope,uiGmapLogger, uiGmapGoogleMapApi, $state, $stateParams, $timeout, $mdDialog) {

Display google map directions when page load

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!');
});
}
});
}
});
})

AngularJS Ionic Leaflet - Map markers not showing

So Ive been trying to get leaflet working in an Ionic app and everything is working fine except my markers. They are not being shown in the default screen nor the locate() function. below is my code
html snippet
<leaflet defaults="map.defaults" center="map.center" markers="map.markers" ng-if="map"></leaflet>
controller
app.controller('MapController',function($scope, $cordovaGeolocation, $stateParams) {
$scope.$on("$stateChangeSuccess", function() {
$scope.map = {
defaults: {
tileLayer: 'http://{s}.tile.osm.org/{z}/{x}/{y}.png',
maxZoom: 18,
zoomControlPosition: 'bottomleft'},
center: {
lat : 20.6219444444,
lng : -105.228333333,
zoom : 15},
markers: {
lat : 20.6219444444,
lng : -105.228333333,
message: "Puerto Vallarta, MX",
focus: true,
draggable: false}
};
});
$scope.locate = function(){
$cordovaGeolocation
.getCurrentPosition()
.then(function (position) {
$scope.map.center.lat = position.coords.latitude;
$scope.map.center.lng = position.coords.longitude;
$scope.map.center.zoom = 16;
$scope.map.markers.now = {
lat:position.coords.latitude,
lng:position.coords.longitude,
message: "You Are Here",
focus: true,
draggable: false
};
}, function(err) {
// error
console.log("Location error!");
console.log(err);
});
};
});
any ideas?? thanks for looking
SOLVED
I added marker value to a variable and then copied that into the $scope.map
here is the updated working controller
app.controller('MapController',function($scope, $cordovaGeolocation, $stateParams) {
$scope.$on("$stateChangeSuccess", function() {
var mainMarker = {
lat: 20.6219444444,
lng: -105.228333333,
focus: true,
message: "Puerto Vallarta, MX",
draggable: false};
$scope.map = {
defaults: {
tileLayer: 'http://{s}.tile.osm.org/{z}/{x}/{y}.png',
maxZoom: 18,
zoomControlPosition: 'bottomleft'},
center: {
lat : 20.6219444444,
lng : -105.228333333,
zoom : 15},
markers: {
mainMarker: angular.copy(mainMarker)}
};
});
$scope.locate = function(){
$cordovaGeolocation
.getCurrentPosition()
.then(function (position) {
$scope.map.center.lat = position.coords.latitude;
$scope.map.center.lng = position.coords.longitude;
$scope.map.center.zoom = 16;
$scope.map.markers.now = {
lat:position.coords.latitude,
lng:position.coords.longitude,
message: "You Are Here",
focus: true,
draggable: false
};
}, function(err) {
// error
console.log("Location error!");
console.log(err);
});
};
});

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
});
}):

Resources