Google Maps Geocoder Marker is not working on AngularJS - javascript

I'm working with the Google Maps Geocoder service for AngularJS framework, but hadn't been able to show any markers so far.
Everything else seems to be working fine, but I really need the markers.
Here's my app.js:
angular.module('modelApp', ['ngAnimate', 'ui.bootstrap', 'google-maps'])
.factory('MarkerCreatorService', function () {
var markerId = 0;
function create(latitude, longitude) {
var marker = {
options: {
animation: 1,
labelAnchor: "28 -5",
labelClass: 'markerlabel'
},
latitude: latitude,
longitude: longitude,
id: ++markerId
};
return marker;
}
function invokeSuccessCallback(successCallback, marker) {
if (typeof successCallback === 'function') {
successCallback(marker);
}
}
function createByAddress(address, successCallback) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address' : address}, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
var firstAddress = results[0];
var latitude = firstAddress.geometry.location.lat();
var longitude = firstAddress.geometry.location.lng();
var marker = create(latitude, longitude);
var results = results[0];
invokeSuccessCallback(successCallback, marker);
} else {
alert("Unknown address: " + address);
}
});
}
return {
create: create,
createByAddress: createByAddress
};
})
.controller('modelCtrl', function ($scope, $http, $timeout, $q, $log, MarkerCreatorService){
// $ajax Init
$scope.model= [];
$http.get('resources/model.json')
.success(function(data){
$scope.model= data;
})
$scope.address = '';
$scope.map = {
center: {
latitude: 0,
longitude: 0
},
zoom: 2,
markers: [],
control: {},
options: {
scrollwheel: false
}
};
$scope.map.markers.push($scope.autentiaMarker);
$scope.addAddress = function() {
var address = $scope.address;
if (address !== '') {
MarkerCreatorService.createByAddress(address, function(marker) {
$scope.map.markers.push(marker);
refresh(marker);
});
}
};
function refresh(marker) {
$scope.map.control.refresh({
latitude: marker.latitude,
longitude: marker.longitude});
$scope.map.zoom = 5;
}
})
Here's the index.html:
<google-map center="map.center"
zoom="map.zoom"
draggable="true"
options="map.options"
control="map.control">
<markers models="map.markers" coords="'self'" options="'options'"
isLabel="true">
</marker>
</google-map>
So, I basically need to show the markers. Do you have any idea about what's wrong with my code?
Any help would be appreciated.

One approach is to convert the callback-based API to a promise-based API:
app.factory('MarkerCreatorService', function ($q) {
//...
function createByAddress(address) {
var geocoder = new google.maps.Geocoder();
var deferred = $q.defer();
geocoder.geocode({'address' : address}, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
var firstAddress = results[0];
var latitude = firstAddress.geometry.location.lat();
var longitude = firstAddress.geometry.location.lng();
var marker = create(latitude, longitude);
var results = results[0];
deferred.resolve(marker);
} else {
alert("Unknown address: " + address);
deferred.reject("Unknown address: " + address);
}
});
return deferred.promise;
}
//...
});
Usage
$scope.addAddress = function() {
var address = $scope.address;
if (address !== '') {
MarkerCreatorService.createByAddress(address).then(function(marker) {
$scope.map.markers.push(marker);
refresh(marker);
});
}
};
By converting it to AngularJS promise, it integrates the API into the AngularJS framework and its digest cycle. Only operations which are applied in the AngularJS execution context will benefit from AngularJS data-binding, exception handling, property watching, etc.

Related

AngularJS - not getting return value to controller or view

I'm doing a geolocation and reverse geocoding application. Function is bound to a button-click to call a function in my controller to my service. The service works somewhat, it's getting values but I cannot get it to return the value to my controller.
I previously had some more issues with promises and returns and some of it I solved but obviously not all. Help is appreciated.
My service 'geoService':
(function() {
'use strict';
angular.module('JourneyApp').factory('geoService',
[
'$q',
function($q) {
var geoServiceFactory = {};
function getLocation(location) {
var deferred = $q.defer();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, error);
} else {
console.log("No support for Geolocation");
deferred.reject(false);
}
return deferred.promise;
}
function error(error) {
console.log(error);
}
function showPosition(position) {
var deferred = $q.defer();
var geocoder = new google.maps.Geocoder();
var coords = position.coords;
var latlng = { lat: parseFloat(coords.latitude), lng: parseFloat(coords.longitude) };
geocoder.geocode({ 'location': latlng },
function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
console.log(results);
if (results[0]) {
var formattedAddress = results[0].formatted_address;
console.log(formattedAddress);
deferred.resolve(formattedAddress);
} else {
console.log("No match, sorry");
deferred.reject("Error");
}
} else {
console.log("Error, sorry");
deferred.reject("Error");
}
});
return deferred.promise;
}
geoServiceFactory.getLocation = getLocation;
geoServiceFactory.showPosition = showPosition;
return geoServiceFactory;
}
]);
})();
And this is my controller:
(function() {
'use strict';
angular.module('JourneyApp').controller('tripsController',
[
'tripsService', 'vehicleService', 'geoService', function(tripsService, vehicleService, geoService) {
//'tripsService', function (tripsService) {
var vm = this;
// Get start geolocation
vm.getStartLocation = function() {
geoService.getLocation().then(function (location) {
vm.trip.startAdress = location;
});
}
// Get stop geolocation
vm.getStopLocation = function() {
geoService.getLocation().then(function(location) {
vm.trip.stopAdress = location;
});
}
}
]);
}());
And parts of my view:
<div class="col-md-2">
<input ng-model="vm.trip.startAdress"/>
</div>
<div class="col-md-2">
<button ng-click="vm.getStartLocation()">Get location</button>
</div>
What am I doing wrong here and how do I fix it?
As mentioned in my comment the promise created in getLocation is never resolved and thus the value never stored. The following should do the trick(replace the if in getLocation with this code):
[...]
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
showPosition(position).then(function(formattedAddress) {
deferred.resolve(formattedAddress);
}
}, error);
} else {
[...]

Meteor implementing Google Maps and Google Places

I'm attempting to implement a Google Map on my Meteor app that will get the user's location and then will find places that serve food near the user. I began by implementing the example
given by Google, and it worked fine when I did it that way; however I'm trying to implement it properly by adding it to the actual Javascript file and it is now giving me a "Google is undefined" error.
menuList = new Mongo.Collection('items');
if (Meteor.isClient) {
var pls;
var map;
var infowindow;
Meteor.startup(function () {
//get user location and return location in console
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
function success(pos) {
var crd = pos.coords;
console.log('Your current position is:');
console.log('Latitude : ' + crd.latitude);
console.log('Longitude: ' + crd.longitude);
console.log('More or less ' + crd.accuracy + ' meters.');
pls = {lat: crd.latitude, lng: crd.longitude};
};
function error(err) {
console.warn('ERROR(' + err.code + '): ' + err.message);
};
navigator.geolocation.getCurrentPosition(success, error, options);
})
Meteor.methods({
callback: function (results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
},
createMarker: function (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);
});
}
})
Template.searchIt.helpers({
'initMap': function () {
console.log("HERE");
//Dummy values I placed for StackOverflow
var pyrmont = {lat: -33.234, lng: 95.343};
map = new google.maps.Map(document.getElementById('map'), {
center: pyrmont,
zoom: 15
});
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: pyrmont,
radius: 500,
types: ['food']
}, callback);
}
})
}
<head>
<title>Place searches</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyACgaDFJrh2pMm-bSta1S40wpKDDSpXO2M
&signed_in=true&libraries=places" async defer></script>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
</style>
</head>
<body>
{{>searchIt}}
</body>
<template name="searchIt">
{{initMap}}
</template>
You should try the dburles:google-maps package.
Here is an example written by its author: http://meteorcapture.com/how-to-create-a-reactive-google-map/
Have fun!
i had to place the code you have above inside of a GoogleMaps.ready('map', callback) block. or inside of an if (GoogleMaps.loaded()) {} block...
for instance.. this works just fine:
caveat: i'm using the radarSearch, but the concept is the same.
Template.galleryCard.onRendered(function() {
GoogleMaps.ready('minimap', function(map) {
const params = {
map: map,
name: 'The Spice Suite',
loc: {lat: 38.9738619, lng: -77.01829699999999},
};
const service = new google.maps.places.PlacesService(params.map.instance);
let request2 = {
//name & location & radius (meters).
name: params.name,
location: params.loc,
radius: 100,
};
let callback = function(results,status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
console.log(results[0]);
return results[0].place_id;
} else {
console.log(status);
}
};
service.radarSearch(request2,callback);
});
});

Unknown provider using leafletView to display popup in Angular Leaflet Directive

I am trying to display a pop up window in an angular leaflet map using prune cluster. However, I am getting an error that leafletView is an unknown provider. I have followed the examples on this page but i have been unsuccessful - https://github.com/SINTEF-9012/PruneCluster. Here is my code:
angular.module('bizvizmap').controller('controller', [
'$scope', '$http', '$filter', 'leafletData', 'leafletView',
function ($scope, $http, $filter, leafletData, leafletView){
$scope.center = {
lat: 39.5500507,
lng: -105.7820674,
zoom: 4
},
$scope.defaults = {
scrollWheelZoom: true
},
$scope.events = {
map: {
enable: ['zoomstart', 'drag', 'click', 'mousemove'],
logic: 'emit'
}
},
$scope.layers = {
baselayers: {
osm: {
name: 'OpenStreetMap',
url: 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
type: 'xyz'
}
},
markers:{}
},
$scope.map = null;
leafletData.getMap("bizvizmap").then(function(map){
$scope.map = map;
});
function renderMarkers(data, map){
var markerLayer = new PruneClusterForLeaflet();
for (var i=0; i < data.length; i++){
var marker = new PruneCluster.Marker(data[i].geometry.coordinates[1], data[i].geometry.coordinates[0]);
popup: "Marker";
markerLayer.RegisterMarker(marker);
}
map.addLayer(markerLayer);
markerLayer.ProcessView();
}
//Display PopUp
leafletView.PrepareLeafletMarker = function (marker, data) {
if (marker.getPopup()) {
marker.setPopupContent(data.company);
} else {
marker.bindPopup(data.company);
}
};
$scope.geojson = {};
$http.get('data/bizvizmap.geojson').success(function (data){
$scope.data = data;
// Render clustered markers
renderMarkers(data.features, $scope.map);
});
// Filtering markers
$scope.search = {
'NAICS':'',
'SIC':''
};
$scope.$watch('search', function(newVal, oldVal){
if(!angular.equals(newVal, oldVal)) {
var geojson = angular.copy($scope.data);
angular.forEach(newVal, function(value, property){
console.log(property + ':' + value);
if (value !== ''){
geojson = $filter('filter')(geojson, property, value);
}
});
function removeMarkers(data, map){
map.removeLayer(markerLayer);
markerLayer.ProcessView();
}
//map.removeLayer(markerLayer);
// Remove all the markers
$scope.geojson.data = geojson;
//renderMarkers(data.features, $scope.map);
} else {
$scope.geojson.data = $scope.data;
}
}, true);
}
]);
I think that the object that have to be modified in order to add popups is the actual prunecluster were you are registering the markers.
var markerLayer = new PruneClusterForLeaflet();
markerLayer.PrepareLeafletMarker = function (marker, data) {
if (marker.getPopup()) {
marker.setPopupContent(data.company);
} else {
marker.bindPopup(data.company);
}
};

Multiple markers on google maps using json and placeid

the problem i've got is that I don't know where the problem is :P
From the beginning. I've got 3 files, the json file JS and html. JS should get placeid from json and based on that place a marker on the map. It's all pretty simple but somehow it doesn't work, the map is being created but no markers show up.
Here're the files:
JSON:
[{ "placeid": 'ChIJu6HrLMVWIkcRWHTA90kiueI' , "content": " 1 " } ,
{ "placeid": 'ChIJnXBuJ34zGUcRvt9FTKrPeeM' , "content": " 2 " } ,
{ "placeid": 'ChIJiwUNhqX7PEcRdJjYqzrWYjs' , "content": " 3 " } ]
HTML:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script src="http://code.jquery.com/jquery-migrate-1.1.1.min.js"></script>
<script src="functions_edit.js"></script>
</head>
<body>
<div id="map-canvas" style="width:500px; height:400px"></div>
</body>
</html>
JS:
var openedInfoWindow = null;
function initialize() {
var latitude = 51.9315631,
longitude = 19.473451,
radius = 8000,
center = new google.maps.LatLng(latitude,longitude),
mapOptions = {
center: center,
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
setMarkers(center, radius, map);
}
function setMarkers(center, radius, map) {
var json = (function () {
var json = null;
$.ajax({
'async': false,
'global': false,
'url': "placeid.json",
'dataType': "json",
'success': function (data) {
json = data;
}
});
return json;
})();
for (var i = 0, length = json.length; i < length; i++) {
var data = json[i];
var service = new google.maps.places.PlacesService(map);
service.getDetails({
placeId: data.placeid
}, function (result, status) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
var marker = new google.maps.Marker({
map: map,
place: {
placeId: data.placeid,
location: result.geometry.location
}
//position: result.geometry.location
});
});
infoBox(map, marker, data);
}
}
function infoBox(map, marker, data) {
var infoWindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, "click", function(e) {
infoWindow.setContent(data.content);
infoWindow.open(map, marker);
});
(function(marker, data) {
google.maps.event.addListener(marker, "click", function(e) {
infoWindow.setContent(data.content);
infoWindow.open(map, marker);
});
})(marker, data);
}
google.maps.event.addDomListener(window, 'load', initialize);
With the posted code I get a javascript error: Uncaught ReferenceError: marker is not defined
You are calling the InfoBox function in the wrong place (outside the scope where marker exists).
Once I fix that I get infowindows, but you have an issue that can be solved by function closure (all the infowindows have the content "3", the last marker processed). (For an example of function closure see Google Maps JS API v3 - Simple Multiple Marker Example)
working fiddle
code snippet:
var placeid_json = [{
"placeid": 'ChIJu6HrLMVWIkcRWHTA90kiueI',
"content": " 1 "
}, {
"placeid": 'ChIJnXBuJ34zGUcRvt9FTKrPeeM',
"content": " 2 "
}, {
"placeid": 'ChIJiwUNhqX7PEcRdJjYqzrWYjs',
"content": " 3 "
}];
var openedInfoWindow = null;
function initialize() {
var latitude = 51.9315631,
longitude = 19.473451,
radius = 8000,
center = new google.maps.LatLng(latitude, longitude),
mapOptions = {
center: center,
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
setMarkers(center, radius, map);
}
function setMarkers(center, radius, map) {
/* var json = (function () {
var json = null;
$.ajax({
'async': false,
'global': false,
'url': "placeid.json",
'dataType': "json",
'success': function (data) {
json = data;
}
});
return json;
})(); */
var json = placeid_json;
for (var i = 0, length = json.length; i < length; i++) {
var data = json[i];
createMarker(data, map);
}
}
function createMarker(data, map) {
var service = new google.maps.places.PlacesService(map);
service.getDetails({
placeId: data.placeid
}, function (result, status) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
var marker = new google.maps.Marker({
map: map,
place: {
placeId: data.placeid,
location: result.geometry.location
}
//position: result.geometry.location
});
infoBox(map, marker, data, result);
});
}
function infoBox(map, marker, data, result) {
var infoWindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.content);
infoWindow.open(map, marker);
});
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.content+"<br>"+result.name);
infoWindow.open(map, marker);
});
})(marker, data);
}
google.maps.event.addDomListener(window, 'load', initialize);
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map-canvas" style="width:500px; height:400px"></div>

Update to $scope object in AngularJS Service does not update View

I'm trying to implement Google maps in Angular / IonicFramework. I'm using a directive, a service, and a controller. I have a map, marker, and geolocation object in $scope. The map object and the marker object in the view updates from the service however the geolocation object doesn't.
The template/view:
<div class="item item-input item-stacked-label item-icon-right">
<div>
Location
<a ng-click="centerOnMe()">
<i class="icon ion-android-locate" style="font-size:24px"></i>
</a>
</div>
<textarea style="margin-top: 0px; margin-bottom: 0px; height: 45px;" placeholder="Location not found." disabled>{{geoloc.addr}}</textarea>
</div>
<div class="item item-input">
<div class="input-label">Map</div>
</div>
<div class="item item-input" style="height:15em;">
<ion-content scroll="false">
<map on-create="mapCreated(map, geoloc, marker)"></map>
</ion-content>
</div>
The map directive:
angular.module('starter.directives', [])
.directive('map', function(MapService) {
return {
restrict: 'E',
scope: {
onCreate: '&'
},
link: function ($scope, $element, $attr) {
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(43.07493, -89.381388),
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map($element[0], mapOptions);
var geoloc = {
lat: null, lng: null, str: null, brgy: null,
muni: null, reg: null, addr: null
};
var marker = new google.maps.Marker({
map: map
});
$scope.onCreate(
{
map: map, //link map to map in controller
geoloc: geoloc, //link geoloc to geoloc in controller
marker: marker //link marker to marker in controller
});
// Stop the side bar from dragging when mousedown/tapdown on the map
google.maps.event.addDomListener($element[0], 'mousedown', function (e) {
e.preventDefault();
return false;
});
}
if (document.readyState === "complete") {
initialize();
} else {
google.maps.event.addDomListener(window, 'load', initialize);
}
}
}
});
The map controller:
angular.module('starter.controllers', [])
.controller('MapCtrl', function($scope, $ionicLoading, MapService) {
$scope.mapCreated = function(map, geoloc, marker) {
$scope.map = map; //sets the map from the directive to the $scope
$scope.geoloc = geoloc; //sets the geoloc from the directive to the $scope
$scope.marker = marker; //sets the marker from the directive to the $scope
};
$scope.centerOnMe = function () {
console.log('Centering..');
if (!$scope.map && !$scope.marker && !$scope.geoloc) {
return;
}
$scope.loading = $ionicLoading.show({
template: 'Getting current location...',
noBackdrop: true
});
$scope.geoloc = MapService.getCurrentLocation($ionicLoading, $scope.map, $scope.geoloc, $scope.marker);
// ^^^ This doesn't seem to work. $scope.geoloc doesn't get updated immediately, while $scope.map and $scope.marker gets updated immediately. Has to be invoked twice for $scope.geoloc to be updated.
}
});
The map service:
angular.module('starter.services', [])
.factory('MapService', function() {
return {
getCurrentLocation: function($ionicLoading, map, geoloc, marker) {
navigator.geolocation.getCurrentPosition(function (pos) { //callback if get location succeeds
geoloc.lat = pos.coords.latitude;
geoloc.lng = pos.coords.longitude;
var latlngpos = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'latLng': latlngpos}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
map.setZoom(16);
marker.setOptions({
position: latlngpos,
map: map
});
geoloc.str = results[0].address_components[0].short_name; //type:route
geoloc.brgy = results[0].address_components[1].short_name; //type:neighborhood
geoloc.muni = results[0].address_components[2].short_name; //type:locatlity
geoloc.reg = results[0].address_components[3].short_name; //type:admnistrative_area_level_1
geoloc.addr = results[0].formatted_address;
} else {
console.log('No results found');
}
} else {
console.log('Geocoder failed due to: ' + status);
}
});
map.setCenter(latlngpos);
$ionicLoading.hide();
}, function (error) { //callback if get location fails
alert('Unable to get location: ' + error.message);
});
return geoloc;
}
}
})
;
I based my implementation here:
http://www.jeffvandalsum.com/integrating-google-maps-api-with-angular/
And I already followed the solutions as suggested here, however the $scope.geoloc object still doesn't update:
Angular directive scope between google maps and a controller
Phonegap not firing GoogleMaps v3 domListener function inside Angularjs directive
Try wrapping
$scope.geoloc = MapService.getCurrentLocation($ionicLoading,$scope.map, $scope.geoloc, $scope.marker);
with $timeout
angular.module('starter.controllers', [])
.controller('MapCtrl', function($scope,$timeout, $ionicLoading, MapService) {
$scope.mapCreated = function(map, geoloc, marker) {
$scope.map = map; //sets the map from the directive to the $scope
$scope.geoloc = geoloc; //sets the geoloc from the directive to the $scope
$scope.marker = marker; //sets the marker from the directive to the $scope
};
$scope.centerOnMe = function () {
console.log('Centering..');
if (!$scope.map && !$scope.marker && !$scope.geoloc) {
return;
}
$scope.loading = $ionicLoading.show({
template: 'Getting current location...',
noBackdrop: true
});
$timeout(function(){
$scope.geoloc = MapService.getCurrentLocation($ionicLoading, $scope.map, $scope.geoloc, $scope.marker);
// ^^^ This doesn't seem to work. $scope.geoloc doesn't get updated immediately, while $scope.map and $scope.marker gets updated immediately. Has to be invoked twice for $scope.geoloc to be updated.
});
}
});
Side Note: This isn't necessarily the best way, but it should trigger your $scope.geoloc to to update correctly.
I would also suggest Gajotres's tutorial.
Hope this was helpful!
I just rewrote my directive, service, and controller, and now it's working. the data now is contained in the service. Then I just injected the service to the directive and the controller.
The map service:
.factory('MapService', function() {
var service = {};
service.map = null;
service.marker = null;
service.geoloc = {
lat: 0.0,
lng: 0.0,
str: "",
brgy: "",
muni: "",
reg: "",
addr: ""
};
service.init = function(map, marker) {
this.map = map;
this.marker = marker;
}
service.getCurrLoc = function($ionicLoading) {
navigator.geolocation.getCurrentPosition(function (pos) { //callback if get location succeeds
service.geoloc.lat = pos.coords.latitude;
service.geoloc.lng = pos.coords.longitude;
var latlngpos = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
var geocoder = new google.maps.Geocoder();
service.marker = new google.maps.Marker({
position: latlngpos,
map: service.map
});
//get location
geocoder.geocode({'latLng': latlngpos}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
service.map.setZoom(16);
service.marker.setOptions({
position: latlngpos,
map: service.map
});
service.geoloc.str = results[0].address_components[0].short_name; //type:route
service.geoloc.brgy = results[0].address_components[1].short_name; //type:neighborhood
service.geoloc.muni = results[0].address_components[2].short_name; //type:locatlity
service.geoloc.reg = results[0].address_components[3].short_name; //type:admnistrative_area_leveservice
service.geoloc.addr = results[0].formatted_address;
service.map.setCenter(latlngpos);
$ionicLoading.hide(); //hide loading prompt
} else {
console.log('No results found');
}
} else {
console.log('Geocoder failed due to: ' + status);
}
});
},
function (error) { //callback if get location fails
},
{ enableHighAccuracy: true }); //geolocation options
}
return service;
})
The map directive:
.directive('map', ["MapService", function(MapService) {
return {
restrict: 'E',
scope: {
onCreate: '&'
},
link: function ($scope, $element, $attr) {
function initialize() {
var mapOptions = {
//set to Philippines
center: new google.maps.LatLng(14.6839606, 121.0622039),
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
MapService.map = new google.maps.Map($element[0], mapOptions);
MapService.marker = new google.maps.Marker({
map: MapService.map
});
$scope.onCreate(
{
map: MapService.map, //link map to map in controller
marker: MapService.marker, //link marker to marker in controller
geoloc: MapService.geoloc //link geoloc to geoloc in controller
}
);
// Stop the side bar from dragging when mousedown/tapdown on the map
google.maps.event.addDomListener($element[0], 'mousedown', function (e) {
e.preventDefault();
return false;
});
}
if (document.readyState === "complete") {
initialize();
} else {
google.maps.event.addDomListener(window, 'load', initialize);
}
}
}
}])
The map controller:
.controller('MapCtrl', ["$scope", "$ionicLoading", "MapService", function($scope, $ionicLoading, MapService) {
$scope.mapCreated = function(map, marker, geoloc) {
$scope.map = map; //sets the map from the directive to the $scope
$scope.marker = marker; //sets the marker from the directive to the $scope
$scope.geoloc = geoloc; //sets the geoloc from the directive to the $scope
console.log('$scope.geoloc in $scope.mapCreated', $scope.geoloc);
$scope.centerOnMe();
};
$scope.centerOnMe = function () {
console.log("Centering");
if (!$scope.geoloc && !$scope.map && !$scope.marker) {
console.log($scope.map);
console.log($scope.marker);
console.log($scope.geoloc);
return;
}
$scope.loading = $ionicLoading.show({
template: 'Getting current location...',
noBackdrop: true
});
MapService.getCurrLoc($ionicLoading);
}
}])

Categories