We'll begin by creating a basic vector layer. Start a new page using the sandbox template. We'll use some existing vector data (found in the assets/data folder of the sample code that comes with this book) that contains polygons outlining countries of the world and display it in a map:
<script> tag to create our vector layer:var vectorSource = new ol.source.GeoJSON({
projection: 'EPSG:3857',
url: '../assets/data/countries.geojson'
});
var vectorLayer = new ol.layer.vector({
source: vectorSource
});var center = ol.proj.transform([0, 0], 'EPSG:4326', 'EPSG:3857');
var view = new ol.View ({
center: center,
zoom: 1,
});map variable and add the vector layer the same way you would add any other layer:var map = new ol.Map({
target: 'map',
layers: [vectorLayer],
view: view
});
Zoom in on the countries and notice how quickly the map zooms and how sharp the outlines of the countries remain.
We just demonstrated how easy it is to incorporate vector data into a map. First, we created a source, specifically one that knows how to read features in the GeoJSON format. We told the source where to find the data (its url property) and what projection we need the data to be in (The view's projection is EPSG:3857, a standard Spherical Mercator projection used in many common commercial maps such as Google and Bing. We'll discuss projections in more detail in Chapter 7, Wrapping Our Heads Around Projections). Next, we created a vector layer and provided it with the source we just created. The view object centers the map at 0 degrees latitude and longitude, and we added all of this to the map in the same way we've used in all the other examples.
Vector layers tend to be very quick, as the data can be stored entirely on the client. Interaction happens instantly, which can greatly enhance the user's experience. Which of the following would be good choices for using vector layers?
Now, before we jump into more advanced uses of the vector layer, first, let's see how it actually works.