(function(window, document) {
'use strict';
var angular = window.angular;
var module = angular.module('App', []);
module.controller('Main', [
'$scope',
'mapService',
function($scope, map) {
$scope.Main = this;
this.onClickOSM = function() {
map.change(map.BASE.OSM);
};
this.onClickForest = function() {
map.change(map.BASE.FOREST);
};
this.onClickTransport = function() {
map.change(map.BASE.TRANSPORT);
};
}
]);
module.directive('map', [
'mapService',
function(mapInstance) {
return {
'restrict' : 'E',
'template' : function() {
return '<div id="map_canvas"></div>';
},
'scope' : false,
'link' : function(scope, element, attrs, ctrl) {
mapInstance.initialize('map_canvas');
}
}
}
])
module.factory('mapService', [
function() {
var OpenLayers = window.OpenLayers;
var _map = null;
var _baseLayers = [];
var BASE = {
'OSM' : 0,
'FOREST' : 1,
'TRANSPORT' : 2,
};
var EPSG = {
'_4326' : 'EPSG:4326',
'_3857' : 'EPSG:3857',
}
var _addBaseLayers = function() {
_baseLayers[BASE.OSM] = new OpenLayers.Layer.XYZ(
'OpenStreetMap',
[
'https://a.tile.openstreetmap.org/${z}/${x}/${y}.png',
'https://b.tile.openstreetmap.org/${z}/${x}/${y}.png',
'https://c.tile.openstreetmap.org/${z}/${x}/${y}.png',
]
);
_baseLayers[BASE.FOREST] = new OpenLayers.Layer.XYZ(
'Forest',
[
'https://a.tile.thunderforest.com/landscape/${z}/${x}/${y}.png',
'https://b.tile.thunderforest.com/landscape/${z}/${x}/${y}.png',
'https://c.tile.thunderforest.com/landscape/${z}/${x}/${y}.png',
]
);
_baseLayers[BASE.TRANSPORT] = new OpenLayers.Layer.XYZ(
'Transoprt',
[
'http://a.tile2.opencyclemap.org/transport/${z}/${x}/${y}.png',
'http://b.tile2.opencyclemap.org/transport/${z}/${x}/${y}.png',
]
);
_map.addLayers(_baseLayers);
};
return {
'BASE' : BASE,
'initialize' : function(targetElement) {
_map = new OpenLayers.Map(
targetElement,
{
projection : EPSG._3857,
displayProjectiona : EPSG._4326,
controls: [
new OpenLayers.Control.Navigation(),
new OpenLayers.Control.PanZoomBar(),
],
}
);
_addBaseLayers();
_map.setCenter(new OpenLayers.LonLat(139.023221, 37.902418).transform(EPSG._4326, EPSG._3857), 10);
},
'destory' : function() {
_map.destory();
_map = null;
},
'change' : function(mapEnum) {
var target = _baseLayers[mapEnum];
_map.setBaseLayer(target);
},
};
}
]);
})(window, document);
<div ng-app="App" ng-controller="Main">
<map></map>
<button ng-click="Main.onClickOSM()">OpenStreetMap</button>
<button ng-click="Main.onClickForest()">Forest</button>
<button ng-click="Main.onClickTransport()">Transport</button>
</div>
#map_canvas {
width: 500px;
height: 500px;
}
External resources loaded into this fiddle: