open a info window with event click on google maps with angular - angularjs

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.

Related

Showing google map pinpoints dynamically using angularjs

I am trying to show pin points on google map by matching the location and retreiving list of longitude, latitude saved in the database when user enters location using AngularJS, HTML and Java. Following is my controller code. Please help me achieve my target
app.controller('mapCtrl', function ( $scope, $http) {
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(25,80),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
$scope.map = new google.maps.Map(document.getElementById('map'), mapOptions);
$scope.markers = [];
$scope.cities = [];
$scope.lati = [];
$scope.longi = [];
$scope.desc = [];
var infoWindow = new google.maps.InfoWindow();
$http.get('http://localhost:8080/acudraStore/getCity').
success(function( data){
for(i = 0;i <=3;i++){
$scope.cities.push(data.countryList[i].city);
$scope.lati.push(data.countryList[i].latitude);
$scope.longi.push(data.countryList[i].longitude);
$scope.desc.push(data.countryList[i].desc);
}
var createMarker = function (){
console.log($scope.cities[0]);
var marker = new google.maps.Marker({
map: $scope.map,
position: new google.maps.LatLng($scope.lati[0], $scope.longi[0]),
title: $scope.cities[0]
});
marker.content = '<div class="infoWindowContent">' + $scope.desc[0] + '</div>';
google.maps.event.addListener(marker, 'click', function(){
infoWindow.setContent('<h2>' + marker.title + '</h2>' + marker.content);
infoWindow.open($scope.map, marker);
});
$scope.markers = [];
$scope.markers.push(marker);
$scope.markers = [];
for (i = 0; i < markers.length; i++){
createMarker(markers[i]);
}}
});
$scope.openInfoWindow = function(e, selectedMarker){
e.preventDefault();
google.maps.event.trigger(selectedMarker, 'click');
}
});
The example (similar to the provide in question) demonstrates how to load locations from external resource and display markers with info window:
var app = angular.module('mapApp', []);
app.controller('mapCtrl', function ($scope, $http) {
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(-25.5349952, 125.8554386),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
$scope.map = new google.maps.Map(document.getElementById('map'), mapOptions);
$scope.markers = [];
$scope.cities = [];
var infoWindow = new google.maps.InfoWindow();
$http.get('https://gist.githubusercontent.com/vgrem/dd818d266445f1a653c1/raw/e768daf280bab0791c2c27ae0f3d5952490bc2a5/cities.json').
success(function (data) {
$scope.cities = data.countryList;
$scope.cities.forEach(function(city) {
createMarker(city);
});
});
var createMarker = function(city) {
var marker = new google.maps.Marker({
map: $scope.map,
position: new google.maps.LatLng(city.latitude, city.longitude),
title: city.city
});
marker.content = '<div class="infoWindowContent">' + city.desc + '</div>';
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent('<h2>' + marker.title + '</h2>' + marker.content);
infoWindow.open($scope.map, marker);
});
$scope.markers.push(marker);
};
//$scope.openInfoWindow = function (e, selectedMarker) {
// e.preventDefault();
// google.maps.event.trigger(selectedMarker, 'click');
//}
});
#map {
width: 800px;
height: 600px;
}
<script src="https://code.angularjs.org/1.3.14/angular.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=&v=3.0&sensor=true"></script>
<div ng-app="mapApp" ng-controller="mapCtrl">
<div id="map"></div>
</div>
Plunker

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 object on page load

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
}

Google Maps Angular Js

I'm working on a page which has a map containing many markers and a list on the side of the marker titles. This example helped me get started. http://jsfiddle.net/svigna/pc7Uu/
I have images and descriptions relative to each marker location that I would like to display in the side list only when the associated marker is clicked.
Any ideas in how I could go about implementing this logic? Thanks.
Here is my HTML
<div ng-app="mapsApp" ng-controller="MapCtrl">
<div id="map"></div>
<div id="class" ng-repeat="marker in markers | orderBy : 'title'">
{{marker.title}}
<img ng-src="{{marker.image}}" alt="\{\{album.album\}\} Cover Image" width="300px;" height="300px;">
</div>
</div>
Here is my angular
//Angular App Module and Controller
angular.module('mapsApp', [])
.controller('MapCtrl', function ($scope) {
var mapOptions = {
zoom: 9,
center: new google.maps.LatLng(10.51, 7.432),
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false
}
$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
});
marker.content = '<div class="infoWindowContent">' + info.desc + '</div>';
google.maps.event.addListener(marker, 'click', function(){
infoWindow.setContent('<h2>' + marker.title + '</h2>' + marker.content);
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 JSON
var cities = [
{
location : 'Unguwar Rimi',
desc : "<div id='hook' class='image'><img src=\"images/wells/KA KAF 001 Unguwar Rimi/IMG_4569.JPG\"><br><strong>Kaduna, Nigeria</strong><br>Village: Unguwar Rimi<br>Completed: 2011<br><p>'This borehole is a good blessing, our labor and stress is reduced.'</p></div>",
img: "images/wells/KA KAF 001 Unguwar Rimi/IMG_4569.JPG",
lat : 10.52,
long : 7.43
},
{
location : 'Gidan Bege Kadarko Kagoro',
desc : "<div id='hook' class='image'><img src=\"images/wells/KA KAU 001 Gidon Bege Kadarko Kagoro/IMG_4556.JPG\"><br><strong>Kaduna, Nigeria</strong><br>Village: Unguwar Rimi<br>Completed: 2008<br><p>'God is great, the village no longer has a water problem and we never run short of water.'</p></div>",
img: "images/wells/KA KAU 001 Gidon Bege Kadarko Kagoro/IMG_4556.JPG",
lat : 10.53,
long : 7.27
},
{
location : 'ECWA Seminary Kagoro',
desc : "<div id='hook' class='image'><img src=\"images/wells/KA KAU 002 ECWA Seminary Kagoro/IMG_8123.JPG\"><br><strong>Kaduna, Nigeria</strong><br>Village: ECWA Seminary Kagoro<br>Completed: 2008<br><p>'God is our Savior. He blessed us with this borehole which provides water to our staff and students'</p></div>",
img: "images/wells/KA KAU 002 ECWA Seminary Kagoro/IMG_8123.JPG",
lat : 9.69,
long : 8.39
}
];
You need to set a scope variable to something in the click event.
In your controller:
$scope.selectedMarker = {};
// etc
google.maps.event.addListener(marker, 'click', function(){
infoWindow.setContent('<h2>' + marker.title + '</h2>' + marker.content);
$scope.selectedMarker = marker;
$scope.$apply();
infoWindow.open($scope.map, marker);
});
On your view you can:
<h1>{{selectedMarker.title}}</h1>
Here is a full demo: http://jsfiddle.net/pc7Uu/194/
Also if you want to display HTML (marker's content) on the version of angular you've included (1.1.1) you will need to include ngSanitize.
http://jsfiddle.net/xVGP5/1/

Resources