Reputation: 305
In AngularJS, the id attribute from my HTML Template isn't recognized by my javascript.
For example :
index.html file :
<div ng-controller="SubwayMapController">
<div subway-map></div>
</div>
scripts.js file :
app.directive('subwayMap', function () {
return {
templateUrl: 'Views/subway-map.html'
};
});
map = new OpenLayers.Map("basicMap");
var mapnik = new OpenLayers.Layer.OSM();
var fromProjection = new OpenLayers.Projection("EPSG:4326"); // Transform from WGS 1984
var toProjection = new OpenLayers.Projection("EPSG:900913"); // to Spherical Mercator Projection
var position = new OpenLayers.LonLat(2.35,48.85).transform( fromProjection, toProjection); //Paris
var zoom = 12;
map.addLayer(mapnik);
map.setCenter(position, zoom );
subway-map.html file :
<div id="basicMap"></div>
When I open index page, I expect the map from Openstreetmap to be displayed but nothing happens.
Upvotes: 1
Views: 93
Reputation: 11983
Try setting up the map in the link()
function of the directive. Plus, it looks like you can Map.render()
using a DOMElement instead of needing an ID.
app.directive('subwayMap', function () {
return {
templateUrl: 'Views/subway-map.html',
link: function(scope, element) {
var map = new OpenLayers.Map();
var mapnik = new OpenLayers.Layer.OSM();
var fromProjection = new OpenLayers.Projection("EPSG:4326");
var toProjection = new OpenLayers.Projection("EPSG:900913");
var position = new OpenLayers.LonLat(2.35,48.85)
.transform(fromProjection, toProjection);
var zoom = 12;
map.addLayer(mapnik);
map.setCenter(position, zoom );
map.render(element[0]);
}
};
});
Upvotes: 3
Reputation: 9592
put map access code in setTimeout. You are trying to access the map immediately . Angular ain't done with map rendering yet , so setTimeout
is the solution.
$timeout(function(){
map = new OpenLayers.Map("basicMap");
var mapnik = new OpenLayers.Layer.OSM();
var fromProjection = new OpenLayers.Projection("EPSG:4326"); // Transform from WGS 1984
var toProjection = new OpenLayers.Projection("EPSG:900913"); // to Spherical Mercator Projection
var position = new OpenLayers.LonLat(2.35,48.85).transform( fromProjection, toProjection); //Paris
var zoom = 12;
map.addLayer(mapnik);
map.setCenter(position, zoom );
},10);
Upvotes: 0