Showing google map pinpoints dynamically using angularjs - 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

Related

multiple marker doesn't show up in google map using angualrjs

.controller('homeCtrl', function($scope, Markers) {
var username = window.localStorage.getItem('username');
var id_user = window.localStorage.getItem('id_user');
console.log(username);
console.log(id_user);
document.getElementById('usernameArea').innerHTML = username;
var map = null;
google.maps.event.addDomListener(window, 'load', function() {
var myLatlng = new google.maps.LatLng(-7.977467753377946, 112.63355255126953);
var mapOptions = {
center: myLatlng,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
navigator.geolocation.getCurrentPosition(function(pos) {
map.setCenter(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
//var tes = new google.maps.Latlang();
//var tes = map.setCenter(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
var tes = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
console.log(tes.lat(), tes.lng());
//console.log(tes.lng());
window.localStorage.setItem('lat',tes.lat());
window.localStorage.setItem('lng',tes.lng());
var myLocation = new google.maps.Marker({
position: new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude),
map: map,
title: "My Location"
});
loadMarkers();
});
$scope.map = map;
});
function loadMarkers(){
//Get all of the markers from our Markers factory
Markers.getMarkers().then(function(markers){
console.log("Markers: ", markers);
var records = markers.data.markers;
console.log(records.length);
for (var i = 0; i < records.length; i++) {
var record = records[i];
var markerPos = new google.maps.LatLng(record.latitude, record.longitude);
console.log(record.latitude);
// Add the markerto the map
var marker = new google.maps.Marker({
setMap: map,
animation: google.maps.Animation.DROP,
position: markerPos
});
var infoWindowContent = "<h4>" + record.name + "</h4>";
addInfoWindow(marker, infoWindowContent, record);
}
});
}
function addInfoWindow(marker, message, record) {
var infoWindow = new google.maps.InfoWindow({
content: message
});
google.maps.event.addListener(marker, 'click', function () {
infoWindow.open(map, marker);
});
}
})
this is the result, the marker which get latitude and longitude from database doesn't show up
Okay I have seen the mistake, when you create the marker in your loadMarkers() function you have this:
var marker = new google.maps.Marker({
setMap: map,
animation: google.maps.Animation.DROP,
position: markerPos
});
You are using as key setMap and it's map, so the code should be:
var marker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: markerPos
});

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

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.

AngularJS and GoogleMap

What I am trying is to get latitude and longitude dynamically as I move the marker on map. I found this solution:
google.maps.event.addListener(marker, 'dragend', function(evt){
window.alert(evt.latLng.lat()+"---"+evt.latLng.lng());
});
but its not returning me new values for lat and lng
Here is my code given:
$scope.$on('mapInitialized', function(event, map) {
var uluru;
$scope.postGoogle = function(google){
$http.get("https://maps.googleapis.com/maps/api/geocode/json?address="+google.address+google.city+google.state+google.zip+google.country+"&key="+google.apikey).
then(function(response) {
$scope.latitute = response.data.results[0].geometry.location.lat;
$scope.longitude = response.data.results[0].geometry.location.lng;
uluru = {lat: response.data.results[0].geometry.location.lat, lng: response.data.results[0].geometry.location.lng};
map.setCenter({lat: response.data.results[0].geometry.location.lat, lng: response.data.results[0].geometry.location.lng});
var contentString = '<div id="content">'+
'<div id="siteNotice">'+
'</div>'+
'<h1 id="firstHeading" class="firstHeading">latitude and longitude</h1>'+
'<div id="bodyContent">'+
'<Span>'+map.getCenter()+'</span>'+
'</div>'+
'</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var marker = new google.maps.Marker({
position: uluru,
map: map,
draggable:true,
title: response.data.results[0].formatted_address
});
/* marker.addListener('click', function() {
infowindow.open(map, marker);
});*/
google.maps.event.addListener(marker, 'dragend', function(evt){
/* $scope.latitute = evt.latLng.lat().toFixed(3);
$scope.longitude = evt.latLng.lng().toFixed(3);*/
window.alert(evt.latLng.lat()+"---"+evt.latLng.lng());
//window.alert(this.getPosition().lat());
});
/*google.maps.event.addListener(marker, 'dragstart', function(evt){
//$scope.latitute = '<p>Currently dragging marker...</p>';
window.alert(evt.latLng.lat());
});
*/map.setCenter(marker.position);
marker.setMap(map);
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
//window.alert(google.address+"------"+google.apikey);
};
var numTiles = 1 << map.getZoom();
var projection = new MercatorProjection();
$scope.chicago = map.getCenter();
});
This is what I guess you are looking :
google.maps.event.addListener(marker, 'dragend', function() {
geocoder.geocode({'latLng': marker.getPosition()}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
$('#address').val(results[0].formatted_address);
$('#latitude').val(marker.getPosition().lat());
$('#longitude').val(marker.getPosition().lng());
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
}
}
});
});
Here's a little peice of JavaScript code what I used, to dynamically change lat and lng when marker is moved:
google.maps.event.addListener(marker, 'position_changed', function() {
lat = marker.getPosition().lat();
lng = marker.getPosition().lng();
$('#lat').val(lat);
$('#lng').val(lng);
});
and bottom 2 lines are assigning value to html input, to see, that values are changed

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

Resources