Skip to content

Instantly share code, notes, and snippets.

@borchsenius
Last active September 14, 2017 17:11
Show Gist options
  • Save borchsenius/5a1ec0b48b283ba65021 to your computer and use it in GitHub Desktop.
Save borchsenius/5a1ec0b48b283ba65021 to your computer and use it in GitHub Desktop.
Angular 2 meets Openlayers 3
import {Component, OnInit} from 'angular2/core';
declare var ol: any;
@Component({
selector: 'my-map-app',
template: `<h1>My first openlayers 3 Angular 2 App</h1>
<div id="map" class="map"></div>
`
})
export class AppComponent implements OnInit {
ol: any;
ngOnInit(): void {
var map = new ol.Map({
controls: ol.control.defaults({
attributionOptions: /** @type {olx.control.AttributionOptions} */ ({
collapsible: false
})
}).extend([
new ol.control.ZoomToExtent({
extent: [
813079.7791264898, 5929220.284081122,
848966.9639063801, 5936863.986909639
]
})
]),
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
target: 'map',
view: new ol.View({
projection: 'EPSG:900913',
center: [18.0, 55.4],
zoom: 7
})
});
}
}
<html>
<head>
<title>Angular 2 Openlayers 3 Map QuickStart</title>
<link rel="stylesheet" href="http://openlayers.org/en/v3.12.1/css/ol.css" type="text/css">
<!-- 1. Load libraries -->
<script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="node_modules/rxjs/bundles/Rx.js"></script>
<script src="node_modules/angular2/bundles/angular2.dev.js"></script>
<script src="http://openlayers.org/en/v3.12.1/build/ol.js"></script>
<!-- 2. Configure SystemJS -->
<script>
System.config({
packages: {
app: {
format: 'register',
defaultExtension: 'js'
}
}
});
System.import('app/boot')
.then(null, console.error.bind(console));
</script>
</head>
<!-- 3. Display the map application -->
<body>
<my-map-app>Loading...</my-map-app>
</body>
</html>
@borchsenius
Copy link
Author

Thanks for the feedback. The app.component.ts has been updated with the suggestion to use OnInit instead of constructor from @avbentem and @paweln1986

Copy link

ghost commented Jan 17, 2017

This example is the only way I was able to add OpenLayers to my Angular2 project and display a map.
Any idea how would you go about adding a 'marker'? I'm trying to follow the example in here but it says "cannot read property 'OSM' of undefined" when trying to add the layer to the map created in your variable.

@borchsenius
Copy link
Author

@kzntswsk yep, I created this gist a while ago. Its a map with controls and markers https://gist.github.com/borchsenius/340eb2836051052d7af2
(might be an older version of ol3)

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