Skip to content

Instantly share code, notes, and snippets.

@WaseemTheDream
Last active August 29, 2015 14:07
Show Gist options
  • Save WaseemTheDream/7a72e4ac59f528133822 to your computer and use it in GitHub Desktop.
Save WaseemTheDream/7a72e4ac59f528133822 to your computer and use it in GitHub Desktop.
angular.module('atlasApp').service('MapsService', function(
$scope,
$http,
LocationProvider,
BusInfoProvider) {
var MapsService = {};
MapsService.initMap = function() {
console.log('Initializing');
var mapOptions = {
zoom: 15,
center: $scope.mapCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
};
MapsService.mapCanvas = document.getElementById('map-canvas');
MapsService.map = new google.maps.Map(
MapService.mapCanvas,
mapOptions
);
}
MapsService.showMap = function() {
MapsService.mapCanvas.hidden = false;
}
MapsService.hideMap = function() {
MapsService.mapCanvas.hidden = true;
}
MapsService.plotMarker = function(lat, lng, name) {
var position = new google.maps.LatLng(lat, lng);
$scope.marker = new google.maps.Marker({
position: position,
map: $scope.map,
title: name
});
return position;
};
MapsService.setCenter = function(position) {
MapsService.map.setCenter(position);
};
return {
initMap: MapsService.initMap,
showMap: MapsService.showMap,
hideMap: MapsService.hideMap,
plotMarker: MapsService.plotMarker,
setCenter: MapsService.setCenter
};
});
@WaseemTheDream
Copy link
Author

In plotMarker, we don't necessarily want to setCenter because a lot of markers could be plotted at the same time and maybe we want to call setCenter on the center point of all of the locations of the marker etc.
So setCenter should be a separate function.

var coffeeHouse = Place.get(...);
MapsService.setCenter(
  MapsService.plotMarker(coffeeHouse.lat, coffeeHouse.lng, coffeeHouse.name));

@WaseemTheDream
Copy link
Author

The benefit of structuring the Service like this is:

  • You can refer to MapsService.instanceVariable explicitly instead of this.instanceVariable. this is ambiguous and could be referring to a different object (like in the case of an anonymous inner function).
  • In the return statement on line 49, you only return the functions and objects that are public. So in this gist's example, we do not expose MapsService.mapCanvas so that the user of this service isn't able to mess with that object and accidentally destroy / change it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment