Create firs map
Code :
<!doctype html>
<html>
<head>
<title>OpenLayers Components</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<div id="overlay" style="background-color: yellow; width: 20px; height: 20px;
border-radius: 10px;"></div>
<script src="../assets/ol3/js/ol-debug.js"></script>
<script>
// create a layer with the OSM source
var layer = new ol.layer.Tile({
source: new ol.source.OSM()
});
// create an interaction to add to the map that isn't there by default
var interaction = new ol.interaction.DragRotateAndZoom();
// create a control to add to the map that isn't there by default
var control = new ol.control.FullScreen();
// center on london, transforming to map projection
var center = ol.proj.transform([-1.812, 52.443], 'EPSG:4326', 'EPSG:3857');
// an overlay to position at the center
var overlay = new ol.Overlay({
position: center,
element: document.getElementById('overlay')
});
// view, starting at the center
var view = new ol.View({
center: center,
zoom: 6
});
// finally, the map with our custom interactions, controls and overlays
var map = new ol.Map({
target: 'map',
layers: [layer],
interactions: [interaction],
controls: [control],
overlays: [overlay],
view: view
});
</script>
</body>
</html>
Create map
Code
<!doctype html>
<html>
<head>
<title>OpenLayers Components</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<div id="overlay" style="background-color: yellow; width: 20px; height: 20px;
border-radius: 10px;"></div>
<script src="../assets/ol3/js/ol-debug.js"></script>
<script>
// create a layer with the OSM source
var layer = new ol.layer.Tile({
source: new ol.source.OSM()
});
// create an interaction to add to the map that isn't there by default
var interaction = new ol.interaction.DragRotateAndZoom();
// create a control to add to the map that isn't there by default
var control = new ol.control.FullScreen();
// center on london, transforming to map projection
var center = ol.proj.transform([-1.812, 52.443], 'EPSG:4326', 'EPSG:3857');
// an overlay to position at the center
var overlay = new ol.Overlay({
position: center,
element: document.getElementById('overlay')
});
// view, starting at the center
var view = new ol.View({
center: center,
zoom: 6
});
// finally, the map with our custom interactions, controls and overlays
var map = new ol.Map({
target: 'map',
layers: [layer],
interactions: [interaction],
controls: [control],
overlays: [overlay],
view: view
});
</script>
</body>
</html>
Overlaying information
Code:
<!doctype html>
<html>
<head>
<title>Map Examples</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<input type="checkbox" id="visible" checked> Toggle Layer Visibility
<script src="../assets/ol3/js/ol.js"></script>
<script>
var layer = new ol.layer.Tile({
source: new ol.source.OSM()
});
var london = ol.proj.transform([-0.12755, 51.507222], 'EPSG:4326',
'EPSG:3857');
var view = new ol.View({
center: london,
zoom: 6
});
var map = new ol.Map({
target: 'map',
layers: [layer],
view: view
});
// create a DOM Input helper for the checkbox
var visible = new ol.dom.Input(document.getElementById('visible'));
// and bind its 'checked' property to the layer's 'visible' property
visible.bindTo('checked', layer, 'visible');
</script>
</body>
</html>
Creating map class
Code:
<!doctype html>
<html>
<head>
<title>Map Examples</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<script src="../assets/ol3/js/ol.js"></script>
<script>
// the normal setup for our samples
var layer = new ol.layer.Tile({
source: new ol.source.OSM()
});
var london = ol.proj.transform([-0.12755, 51.507222], 'EPSG:4326',
'EPSG:3857');
var view = new ol.View({
center: london,
zoom: 6
});
var map = new ol.Map({
target: 'map',
layers: [layer],
view: view
});
</script>
</body>
</html>
Target practice
<!doctype html>
<html>
<head>
<title>Map Examples</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div class="map">
<div id="right" class="half-map"></div>
<div id="left" class="half-map"></div>
<div class="panel">
<button onclick="changeTarget();">Change Target</button>
</div>
</div>
<script src="../assets/ol3/js/ol.js"></script>
<script>
var layer = new ol.layer.Tile({
source: new ol.source.OSM()
});
var london = ol.proj.transform([-0.12755, 51.507222], 'EPSG:4326',
'EPSG:3857');
var view = new ol.View({
center: london,
zoom: 6
});
var map = new ol.Map({
target: 'right',
layers: [layer],
view: view
});
// this function is called when the button is clicked.
// Move the map to another div based on its current target.
function changeTarget() {
var target = map.getTarget();
if (target == 'left') {
map.setTarget('right');
} else {
map.setTarget('left');
}
}
</script>
</body>
</html>
Creating animated map
<!doctype html>
<html>
<head>
<title>Animation Examples</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<button onclick="doBounce(london);">Bounce To London</button><br />
<button onclick="doBounce(rome);">Bounce To Rome</button><br />
<button onclick="doPan(london);">Pan To London</button><br />
<button onclick="doPan(rome);">Pan To Rome</button><br />
<button onclick="doRotate();">Rotate</button><br />
<button onclick="doZoom(2);">Zoom Out</button><br />
<button onclick="doZoom(0.5);">Zoom In</button>
<script src="../assets/ol3/js/ol.js"></script>
<script>
var layer = new ol.layer.Tile({
source: new ol.source.OSM()
});
var london = ol.proj.transform([-0.12755, 51.507222], 'EPSG:4326',
'EPSG:3857');
var rome = ol.proj.transform([12.5, 41.9], 'EPSG:4326', 'EPSG:3857');
var view = new ol.View({
center: london,
zoom: 6
});
var map = new ol.Map({
target: 'map',
layers: [layer],
view: view
});
function doBounce(location) {
// bounce by zooming out one level and back in
var bounce = ol.animation.bounce({
resolution: map.getView().getResolution() * 2
});
// start the pan at the current center of the map
var pan = ol.animation.pan({
source: map.getView().getCenter()
});
map.beforeRender(bounce);
map.beforeRender(pan);
// when we set the center to the new location, the animated move will
// trigger the bounce and pan effects
map.getView().setCenter(location);
}
function doPan(location) {
// pan from the current center
var pan = ol.animation.pan({
source: map.getView().getCenter()
});
map.beforeRender(pan);
// when we set the new location, the map will pan smoothly to it
map.getView().setCenter(location);
}
function doRotate() {
// rotate 360 degrees
var rotate = ol.animation.rotate({
rotation: Math.PI * 2
});
map.beforeRender(rotate);
}
function doZoom(factor) {
// zoom from the current resolution
var zoom = ol.animation.zoom({
resolution: map.getView().getResolution()
});
map.beforeRender(zoom);
// setting the resolution to a new value will smoothly zoom in or out
// depending on the factor
map.getView().setResolution(map.getView().getResolution() * factor);
}
</script>
</body>
</html>
Link to view
<!doctype html>
<html>
<head>
<title>Map Examples</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map1" class="half-map"></div>
<div id="map2" class="half-map"></div>
<script src="../assets/ol3/js/ol.js"></script>
<script>
var layer = new ol.layer.Tile({
source: new ol.source.OSM()
});
var london = ol.proj.transform([-0.12755, 51.507222], 'EPSG:4326',
'EPSG:3857');
var view = new ol.View({
center: [-201694.22, 6880651.07],
zoom: 6
});
// create two maps
var map1 = new ol.Map({
target: 'map1',
layers: [layer]
});
var map2 = new ol.Map({
target: 'map2',
layers: [layer],
view: view
});
// and bind the view properties so they effectively share a view
map1.bindTo('view', map2);
</script>
</body>
</html>
Changing layer propertis
<!doctype html>
<html>
<head>
<title>Simple example</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<script src="../assets/ol3/js/ol.js"></script>
<script>
var osmLayer = new ol.layer.Tile({
source: new ol.source.OSM(),
opacity: 0.6,
brightness: 0.2
});
var view = new ol.View({
center: ol.proj.transform([-1.8118500054456526, 52.4431409750608],
'EPSG:4326', 'EPSG:3857'),
zoom: 6
});
var map = new ol.Map({
target: 'map'
});
map.addLayer(osmLayer);
map.setView(view);
/*
console.log(osmLayer.getSource());
osmLayer.setProperties({opacity: 0.4, contrast:0.6});
console.log(osmLayer.get('contrast'));
console.log(osmLayer.get('opacity'));
osmLayer.setProperties({opacity: 0.7, contrast:0.3});
console.log(osmLayer.getOpacity());
console.log(osmLayer.getContrast());
osmLayer.set('opacity',1);
osmLayer.setContrast(1);
osmLayer.setBrightness(0);
osmLayer.set('myId', 'myUnique');
console.log(osmLayer.get('myId'));
*/
</script>
</body>
</html>
Using OSM layer and MapQuest layers to create a map
<!doctype html>
<html>
<head>
<title>Simple example</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<script src="../assets/ol3/js/ol.js"></script>
<script>
var satellite = new ol.layer.Tile({
source: new ol.source.MapQuest({layer: 'sat'})
});
var osm = new ol.layer.Tile({
source: new ol.source.MapQuest({layer: 'osm'})
});
var map = new ol.Map({
layers: [satellite, osm],
target: 'map',
view: new ol.View({
center: ol.proj.transform([-74.044683,40.689848], 'EPSG:4326',
'EPSG:3857'),
zoom: 13
})
});
/*
osm.setVisible(false);
osm.setVisible(true);
*/
</script>
</body>
</html>
Creating a Stamen layer
<!doctype html>
<html>
<head>
<title>Simple example</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<script src="../assets/ol3/js/ol.js"></script>
<script>
var stamenLayer = new ol.layer.Tile({
source: new ol.source.Stamen({
layer: 'toner'
})
});
var map = new ol.Map({
layers: [stamenLayer],
target: 'map',
view: new ol.View({
center: ol.proj.transform([2.35239, 48.858391], 'EPSG:4326', 'EPSG:3857'),
zoom: 12
})
});
</script>
</body>
</html>
Creating a Bing Maps layer
<!doctype html>
<html>
<head>
<title>Simple example</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<script src="../assets/ol3/js/ol.js"></script>
<script>
var sourceBingMaps = new ol.source.BingMaps({
key: 'Ak-dzM4wZjSqTlzveKz5u0d4IQ4bRzVI309GxmkgSVr1ewS6iPSrOvOKhA-CJlm3',
imagerySet: 'Road',
culture: 'fr-FR'
});
var bingMapsRoad = new ol.layer.Tile({
preload: Infinity,
source: sourceBingMaps
});
var bingMapsAerial = new ol.layer.Tile({
preload: Infinity,
source: new ol.source.BingMaps({
key: 'Ak-dzM4wZjSqTlzveKz5u0d4IQ4bRzVI309GxmkgSVr1ewS6iPSrOvOKhA-CJlm3',
imagerySet: 'Aerial',
})
});
var map = new ol.Map({
layers: [bingMapsRoad,bingMapsAerial],
target: 'map',
view: new ol.View({
center: ol.proj.transform([6.562783, 46.517814], 'EPSG:4326', 'EPSG:3857'),
zoom: 13
})
});
</script>
</body>
</html>
Creating tiles and adding Zoomify layer
<!doctype html>
<html>
<head>
<title>Simple example</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<script src="../assets/ol3/js/ol.js"></script>
<script>
var imgWidth = 9945;
var imgHeight = 6846;
var url = '/assets/data/1797-map-of-Dublin/';
var crossOrigin = 'anonymous';
var imgCenter = [imgWidth / 2, - imgHeight / 2];
// Maps always need a projection, but Zoomify layers are not geo-referenced,
and
// are only measured in pixels. So, we create a fake projection that the map
// can use to properly display the layer.
var proj = new ol.proj.Projection({
code: 'ZOOMIFY',
units: 'pixels',
extent: [0, 0, imgWidth, imgHeight]
});
var source = new ol.source.Zoomify({
url: url,
size: [imgWidth, imgHeight],
crossOrigin: crossOrigin
});
var map = new ol.Map({
layers: [
new ol.layer.Tile({
source: source
})
],
target: 'map',
view: new ol.View({
projection: proj,
center: imgCenter,
zoom: 1
})
});
</script>
</body>
</html>
Playing with various sources and layers together
<!doctype html>
<html>
<head>
<title>Playing with various sources and layers</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<script src="../assets/ol3/js/ol.js"></script>
<script>
var bingMapsAerial = new ol.layer.Tile({
preload: Infinity,
source: new ol.source.BingMaps({
key: 'Ak-dzM4wZjSqTlzveKz5u0d4IQ4bRzVI309GxmkgSVr1ewS6iPSrOvOKhA-CJlm3',
imagerySet: 'Aerial'
})
});
bingMapsAerial.set('name', 'Bings Maps Aerial');
var bingMapsRoad = new ol.layer.Tile({
preload: Infinity,
source: new ol.source.BingMaps({
key: 'Ak-dzM4wZjSqTlzveKz5u0d4IQ4bRzVI309GxmkgSVr1ewS6iPSrOvOKhA-CJlm3',
imagerySet: 'Road',
culture: 'fr-FR'
})
});
bingMapsRoad.set('name', 'Bings Maps Road');
var mapQuestAerial = new ol.layer.Tile({
source: new ol.source.MapQuest({layer: 'sat'})
});
mapQuestAerial.set('name', 'MapQuest Open Aerial');
var simpleWMS = new ol.layer.Image({
opacity: 0.6,
source: new ol.source.ImageWMS({
url: 'http://demo.boundlessgeo.com/geoserver/wms',
params: {
'LAYERS': 'topp:states'
},
extent: [-13884991, -7455066, 2870341, 6338219]
})
});
simpleWMS.set('name', 'USA layer from Geoserver WMS demo');
var layers = [bingMapsAerial, bingMapsRoad, mapQuestAerial, simpleWMS];
var map = new ol.Map({
layers: layers,
target: 'map',
view: new ol.View({
center: ol.proj.transform([-90, 40], 'EPSG:4326', 'EPSG:3857'),
zoom: 3
})
});
//Generate checkbox from layers array
function generate_checkbox(id_checkbox, label_name, html_element) {
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.id = id_checkbox;
var label = document.createElement('label');
label.htmlFor = id_checkbox;
label.appendChild(document.createTextNode(label_name));
html_element.appendChild(checkbox);
html_element.appendChild(label);
}
// Loop from the end to get the top layer in first
for (var i = layers.length - 1; i >= 0; i--) {
var id = layers[i].get('id');
var name = layers[i].get('name');
generate_checkbox('layer_id_' + i, name, document.body);
var visible = new ol.dom.Input(document.getElementById('layer_id_' + i));
visible.bindTo('checked', layers[i], 'visible');
}
</script>
</body>
</html>
Applying Zoomify sample knowledge to a single raw image
<!doctype html>
<html>
<head>
<title>Image static sample</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<script src="../assets/ol3/js/ol.js"></script>
<script>
var imgWidth = 9945;
var imgHeight = 6846;
var url = '/assets/data/1797-map-of-Dublin.jpg';
var imgCenter = [imgWidth / 2, imgHeight / 2];
// Maps always need a projection, but Zoomify layers are not geo-referenced,
and
// are only measured in pixels. So, we create a fake projection that the map
// can use to properly display the layer.
var proj = new ol.proj.Projection({
code: 'ZOOMIFY',
units: 'pixels',
extent: [0, 0, imgWidth, imgHeight]
});
var source = new ol.source.ImageStatic({
attributions: [
new ol.Attribution({
html: '© <a href="https://commons.wikimedia.org/wiki/File:1797-map-
of-Dublin.jpg#Summary">Wikipedia Commons</a>'
})
],
url: url,
imageSize: [imgWidth, imgHeight],
projection: proj,
imageExtent: proj.getExtent()
});
var map = new ol.Map({
layers: [
new ol.layer.Image({
source: source
})
],
target: 'map',
view: new ol.View({
projection: proj,
center: imgCenter,
zoom: 1
})
});
</script>
</body>
</html>
Creating a vector layer
<!doctype html>
<html>
<head>
<title>Vector Examples</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<script src="../assets/ol3/js/ol.js"></script>
<script>
// create a vector source that loads a GeoJSON file
var vectorSource = new ol.source.GeoJSON({
projection: 'EPSG:3857',
url: '../assets/data/countries.geojson'
});
// a vector layer to render the source
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
});
// the vector layer gets added like a raster layer
var map = new ol.Map({
target: 'map',
layers: [vectorLayer],
view: view
});
</script>
</body>
</html>
Using the cluster source
<!doctype html>
<html>
<head>
<title>Vector Examples</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<script src="../assets/ol3/js/ol.js"></script>
<script>
// set up a vector source to read the geojson data
var originalSource = new ol.source.GeoJSON({
url: '../assets/data/cluster.geojson'
});
// create a layer from it so we can visualize the original data
var originalLayer = new ol.layer.Vector({
source: originalSource
});
// a clustered source is configured with another vector source that it
// operates on
var clusterSource = new ol.source.Cluster({
source: originalSource
});
// it needs a layer too
var clusterLayer = new ol.layer.Vector({
source: clusterSource
});
// some data to use as the background
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: 2
});
var map = new ol.Map({
target: 'map',
layers: [vectorLayer, clusterLayer],
view: view
});
</script>
</body>
</html>
Creating a loader function
<!doctype html>
<html>
<head>
<title>Vector Examples</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<script src="../assets/ol3/js/ol.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
// a tiled raster layer as the backdrop
var tiledRaster = new ol.layer.Tile({
source: new ol.source.OSM()
});
// styles for the vector layer
var fill = new ol.style.Fill({
color: 'rgba(0,0,0,0.2)'
});
var stroke = new ol.style.Stroke({
color: 'rgba(0,0,0,0.4)'
});
var circle = new ol.style.Circle({
radius: 6,
fill: fill,
stroke: stroke
});
var vectorStyle = new ol.style.Style({
fill: fill,
stroke: stroke,
image: circle
});
// when loading from a features from a remote server, we need to provide
// a loading function that handles the actual communication
// using jQuery's ajax function, we can load the data and ask the WFS
// server to use jsonp and send the results to the loadFeatures function
var vectorLoader = function(extent, resolution, projection) {
var url = 'http://demo.boundlessgeo.com/geoserver/wfs?service=WFS&' +
'version=1.1.0&request=GetFeature&typename=osm:builtup_area&' +
'outputFormat=text/javascript&format_options=callback:loadFeatures' +
'&srsname=EPSG:3857&bbox=' + extent.join(',') + ',EPSG:3857';
$.ajax({
url: url,
dataType: 'jsonp'
});
};
// this will be called when the server data has been loaded, we can
// use the source to read the features using its configured format
var loadFeatures = function(response) {
var features = vectorSource.readFeatures(response);
vectorSource.addFeatures(features);
};
// the source is configured with a format, loader function and a
// strategy, the strategy causes the loader function to be called
// in different ways. With the tile strategy, it will call with
// extents matching tile boundaries for the current zoom level
var vectorSource = new ol.source.ServerVector({
format: new ol.format.GeoJSON(),
loader: vectorLoader,
strategy: ol.loadingstrategy.createTile(new ol.tilegrid.XYZ({
maxZoom: 19
}))
});
// a vector layer, this time with some style options
var serverVector = new ol.layer.Vector({
source: vectorSource,
style: vectorStyle
});
var center = ol.proj.transform([-72.6, 41.7], 'EPSG:4326', 'EPSG:3857');
var view = new ol.View({
center: center,
zoom: 12
});
var map = new ol.Map({
target: 'map',
layers: [tiledRaster, serverVector],
view: view
});
</script>
</body>
</html>
Working with the TileVector source
<!doctype html>
<html>
<head>
<title>Vector Examples</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<script src="../assets/ol3/js/ol.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
var tiledRaster = new ol.layer.Tile({
source: new ol.source.OSM()
});
// some styles for the vector layer
var fill = new ol.style.Fill({
color: 'rgba(0,0,0,0.2)'
});
var stroke = new ol.style.Stroke({
color: 'rgba(0,0,0,0.4)'
});
var circle = new ol.style.Circle({
radius: 6,
fill: fill,
stroke: stroke
});
var vectorStyle = new ol.style.Style({
fill: fill,
stroke: stroke,
image: circle
});
// this time, we'll load vector tiles from openstreetmap
// in the topojson format
var tiledSource = new ol.source.TileVector({
format: new ol.format.TopoJSON({
defaultProjection: 'EPSG:4326'
}),
projection: 'EPSG:3857',
tileGrid: new ol.tilegrid.XYZ({
maxZoom: 19
}),
url:
'http://{a-c}.tile.openstreetmap.us/vectiles-water-areas/{z}/{x}/{y}.topojson'
});
var tiledVector = new ol.layer.Vector({
source: tiledSource,
style: vectorStyle
});
var center = ol.proj.transform([-72.6, 41.7], 'EPSG:4326', 'EPSG:3857');
var view = new ol.View({
center: center,
zoom: 12
});
var map = new ol.Map({
target: 'map',
layers: [tiledRaster, tiledVector],
view: view
});
</script>
</body>
</html>
A drag-and-drop viewer for vector files
<!doctype html>
<html>
<head>
<title>Drag 'n' Drop Vector Example</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<script src="../assets/ol3/js/ol-debug.js"></script>
<script>
var tiledRaster = new ol.layer.Tile({
source: new ol.source.OSM()
});
var fill = new ol.style.Fill({
color: 'rgba(0,0,0,0.2)'
});
var stroke = new ol.style.Stroke({
color: 'rgba(0,0,0,0.4)'
});
var circle = new ol.style.Circle({
radius: 6,
fill: fill,
stroke: stroke
});
var vectorStyle = new ol.style.Style({
fill: fill,
stroke: stroke,
image: circle
});
// the draganddrop interaction allows us to drop files
// onto the browser window. If the file matches one of the
// format constructors, it will automatically extract
// the features from the file and trigger an event
var dragAndDrop = new ol.interaction.DragAndDrop({
formatConstructors: [
ol.format.GPX,
ol.format.GeoJSON,
ol.format.IGC,
ol.format.KML,
ol.format.TopoJSON
]
});
// we can use the event to create a new vector source
// wiht the event's features and projection and add
// it to the map with a new vector layer
dragAndDrop.on('addfeatures', function(event) {
var vectorSource = new ol.source.Vector({
features: event.features,
projection: event.projection
});
map.addLayer(new ol.layer.Vector({
source: vectorSource,
style: vectorStyle
}));
var view = map.getView();
view.fitExtent(vectorSource.getExtent(), map.getSize());
});
var layer = new ol.layer.Tile({
source: new ol.source.OSM()
});
var center = ol.proj.transform([0, 0], 'EPSG:4326', 'EPSG:3857');
var view = new ol.View({
center: center,
zoom: 1
});
var map = new ol.Map({
target: 'map',
layers: [tiledRaster],
view: view
});
// we can add an interaction after creating the map with the default set
map.addInteraction(dragAndDrop);
</script>
</body>
</html>
Geometries in action
<!doctype html>
<html>
<head>
<title>Geometry Examples</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<div id="closestFeature"></div>
<script src="../assets/ol3/js/ol.js"></script>
<script>
var countries = new ol.layer.Vector({
source: new ol.source.GeoJSON({
projection: 'EPSG:3857',
url: '../assets/data/countries.geojson'
})
});
var view = new ol.View({
projection: 'EPSG:3857'
});
var map = new ol.Map({
target: 'map',
layers: [countries],
view: view
});
// zoom to the extent of the vector source once the map has been rendered
// for the first time
map.once('postrender', function() {
view.fitExtent(countries.getSource().getExtent(), map.getSize());
});
// capture mouse move events so we can 'look' at the feature
// underneath the mouse
map.on('pointermove', onMouseMove);
function onMouseMove(browserEvent) {
// the mousemove event sends a browser event object that contains
// the geographic coordinate the event happened at
var coordinate = browserEvent.coordinate;
// we can get the closest feature from the source
var feature =
countries.getSource().getClosestFeatureToCoordinate(coordinate);
// to compute the area of a feature, we need to get it's geometry and do
// something a little different depeneding on the geometry type.
var geometry = feature.getGeometry();
var area;
switch (geometry.getType()) {
case 'MultiPolygon':
// for multi-polygons, we need to add the area of each polygon
area = geometry.getPolygons().reduce(function(left, right) {
return left + right.getArea();
}, 0);
break;
case 'Polygon':
// for polygons, we just get the area
area = geometry.getArea();
break;
default:
// no other geometry types have area as far as we are concerned
area = 0;
}
area = area / 1000000;
// display the country name and area now
var text = feature.getProperties().name + ' ' + area.toFixed(0) + '
km<sup>2</sup>';
document.getElementById('closestFeature').innerHTML = text;
}
</script>
</body>
</html>
Interacting with features
<!doctype html>
<html>
<head>
<title>Vector Style Examples</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<div id="name" style="font-size: 24px;"></div>
<script src="../assets/ol3/js/ol.js"></script>
<script>
var countries = new ol.layer.Vector({
source: new ol.source.GeoJSON({
projection: 'EPSG:3857',
url: '../assets/data/countries.geojson'
})
});
var center = ol.proj.transform([0, 0], 'EPSG:4326', 'EPSG:3857');
var view = new ol.View({
center: center,
zoom: 1
});
var map = new ol.Map({
target: 'map',
layers: [countries],
view: view
});
// when the user moves the mouse, get the name property
// from each feature under the mouse and display it
function onMouseMove(browserEvent) {
var coordinate = browserEvent.coordinate;
var pixel = map.getPixelFromCoordinate(coordinate);
var el = document.getElementById('name');
el.innerHTML = '';
map.forEachFeatureAtPixel(pixel, function(feature) {
el.innerHTML += feature.get('name') + '<br>';
});
}
map.on('pointermove', onMouseMove);
</script>
</body>
</html>
Basic styling
<!doctype html>
<html>
<head>
<title>Vector Style Examples</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<script src="../assets/ol3/js/ol-debug.js"></script>
<script>
// a basic style for the country layer
var countryStyle = new ol.style.Style({
fill: new ol.style.Fill({
color: [203, 194, 185, 1]
}),
stroke: new ol.style.Stroke({
color: [177, 163, 148, 0.5],
width: 2,
lineCap: 'round'
})
});
// a style for the timezones, adding some text
var timezoneStyle = new ol.style.Style({
stroke: new ol.style.Stroke({
color: [64, 200, 200, 0.5],
width: 1
}),
text: new ol.style.Text({
font: '20px Verdana',
text: 'TZ',
fill: new ol.style.Fill({
color: [64, 64, 64, 0.75]
})
})
});
var countries = new ol.layer.Vector({
source: new ol.source.GeoJSON({
projection: 'EPSG:3857',
url: '../assets/data/countries.geojson'
}),
style: countryStyle
});
// make sure we don't use the styles in the KML layer
var timezones = new ol.layer.Vector({
source: new ol.source.KML({
projection: 'EPSG:3857',
url: '../assets/data/timezones.kml',
extractStyles: false
}),
style: timezoneStyle
});
var center = ol.proj.transform([0, 0], 'EPSG:4326', 'EPSG:3857');
var view = new ol.View({
center: center,
zoom: 1
});
var map = new ol.Map({
target: 'map',
layers: [countries, timezones],
view: view
});
</script>
</body>
</html>
The icon style
<!doctype html>
<html>
<head>
<title>Vector Style Examples</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<script src="../assets/ol3/js/ol.js"></script>
<script>
// the icon style allows picking a section out of a larger image
var earthquakeStyle = new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 0.5],
size: [52, 52],
offset: [52, 0],
opacity: 1,
scale: 0.25,
src: '../assets/img/dots.png'
})
});
var countryStyle = new ol.style.Style({
fill: new ol.style.Fill({
color: [0, 255, 255, 1]
}),
stroke: new ol.style.Stroke({
color: [127,127,127,1.0],
width: 1,
lineJoin: 'round'
})
});
var timezoneStyle = new ol.style.Style({
stroke: new ol.style.Stroke({
color: [127,127,127,1.0],
width: 1,
lineJoin: 'round',
lineCap: 'round'
})
});
var countries = new ol.layer.Vector({
source: new ol.source.GeoJSON({
projection: 'EPSG:3857',
url: '../assets/data/countries.geojson'
}),
style: countryStyle
});
var timezones = new ol.layer.Vector({
source: new ol.source.KML({
projection: 'EPSG:3857',
url: '../assets/data/timezones.kml',
extractStyles: false
}),
style: timezoneStyle
});
var earthquakes = new ol.layer.Vector({
source: new ol.source.KML({
projection: 'EPSG:3857',
url: '../assets/data/earthquakes.kml',
extractStyles: false
}),
style: earthquakeStyle
});
var center = ol.proj.transform([0, 0], 'EPSG:4326', 'EPSG:3857');
var view = new ol.View({
center: center,
zoom: 1
});
var map = new ol.Map({
target: 'map',
layers: [countries, timezones, earthquakes],
view: view
});
earthquakes.once('render', function() {
view.fitExtent(earthquakes.getSource().getExtent(), map.getSize());
});
</script>
</body>
</html>
Using multiple styles
<!doctype html>
<html>
<head>
<title>Vector Style Examples</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<script src="../assets/ol3/js/ol.js"></script>
<script>
var shadowStyle = new ol.style.Style({
stroke: new ol.style.Stroke({
color: [0, 0, 127, 0.15],
width: 8
}),
zIndex: 1
});
var countryStyle = new ol.style.Style({
fill: new ol.style.Fill({
color: [203, 194, 185, 1]
}),
stroke: new ol.style.Stroke({
color: [101, 95, 90, 1],
width: 1,
lineCap: 'round'
}),
zIndex: 2
});
// mulitple styles can be combined by using an array of them.
// the order in the array matters!
var countries = new ol.layer.Vector({
source: new ol.source.GeoJSON({
projection: 'EPSG:3857',
url: '../assets/data/countries.geojson'
}),
style: [shadowStyle, countryStyle]
});
var center = ol.proj.transform([0, 0], 'EPSG:4326', 'EPSG:3857');
var view = new ol.View({
center: center,
zoom: 1
});
var map = new ol.Map({
target: 'map',
layers: [countries],
view: view
});
</script>
</body>
</html>
Using properties to style features
<!doctype html>
<html>
<head>
<title>Vector Style Examples</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<script src="../assets/ol3/js/ol.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
// define some colours matching some arbitrary divisions of the
// OECD income data
var high = [64,196,64,1];
var mid = [108,152,64,1];
var low = [152,108,64,1];
var poor = [196,32,32,1];
// map the income level codes to a colour value, grouping them
var incomeLevels = {
'HIC': high, // high income
'OEC': high, // high income OECD
'NOC': high, // high income, non-OECD
'UMC': mid, // upper middle income
'MIC': mid, // middle income
'LMC': mid, // lower middle income
'LIC': low, // low income
'LMY': low, // low and middle income
'HPC': poor // heavily indebted poor country
};
// a default style is good practice!
var defaultStyle = new ol.style.Style({
fill: new ol.style.Fill({
color: [250,250,250,1]
}),
stroke: new ol.style.Stroke({
color: [220,220,220,1],
width: 1
})
});
// a javascript object literal can be used to cache
// previously created styles. Its very important for
// performance to cache styles.
var styleCache = {};
// the style function returns an array of styles
// for the given feature and resolution.
// Return null to hide the feature.
function styleFunction(feature, resolution) {
// get the incomeLevel from the feature properties
var level = feature.get('incomeLevel');
// if there is no level or its one we don't recognize,
// return the default style (in an array!)
if (!level || !incomeLevels[level]) {
return [defaultStyle];
}
// check the cache and create a new style for the income
// level if its not been created before.
if (!styleCache[level]) {
styleCache[level] = new ol.style.Style({
fill: new ol.style.Fill({
color: incomeLevels[level]
}),
stroke: defaultStyle.stroke
});
}
// at this point, the style for the current level is in the cache
// so return it (as an array!)
return [styleCache[level]];
}
var source = new ol.source.GeoJSON({
projection: 'EPSG:3857',
url: '../assets/data/countries.geojson'
});
var countries = new ol.layer.Vector({
source: source,
style: styleFunction
});
var center = ol.proj.transform([0, 0], 'EPSG:4326', 'EPSG:3857');
var view = new ol.View({
center: center,
zoom: 1
});
var map = new ol.Map({
target: 'map',
layers: [countries],
view: view
});
// we want to merge the country data with the income level data. After
// the country data is 'ready', we can load the income level data and
// the add a new property by linking the two sets of data on the
// ISO country code that is present in both data sets.
var key = source.on('change', function(event) {
if (source.getState() == 'ready') {
source.unByKey(key);
$.ajax('../assets/data/income_levels.json').done(function(data) {
countries.getSource().forEachFeature(function(feature) {
var code = feature.get('iso_a2');
if (data[code]) {
feature.set('incomeLevel', data[code]);
}
});
});
}
});
</script>
</body>
</html>
Creating interactive styles
<!doctype html>
<html>
<head>
<title>Geometry Examples</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<script src="../assets/ol3/js/ol-debug.js"></script>
<script>
var countries = new ol.layer.Vector({
source: new ol.source.GeoJSON({
projection: 'EPSG:3857',
url: '../assets/data/countries.geojson'
})
});
var center = ol.proj.transform([0, 0], 'EPSG:4326', 'EPSG:3857');
var view = new ol.View({
center: center,
zoom: 1
});
var map = new ol.Map({
target: 'map',
layers: [countries],
view: view
});
// we want to create text styles based on properties coming from a feature
// to do this, we need to create a new style for each string that needs to
// be represented. All the text styles will share the same properties
// except for the actual text itself. The properties can be set up ahead
// of time in an object literal
var baseTextStyle = {
font: '12px Calibri,sans-serif',
textAlign: 'center',
offsetY: -15,
fill: new ol.style.Fill({
color: [0,0,0,1]
}),
stroke: new ol.style.Stroke({
color: [255,255,255,0.5],
width: 4
})
};
// when we move the mouse over a feature, we can change its style to
// highlight it temporarily
var highlightStyle = new ol.style.Style({
stroke: new ol.style.Stroke({
color: [255,0,0,0.6],
width: 2
}),
fill: new ol.style.Fill({
color: [255,0,0,0.2]
}),
zIndex: 1
});
// the style function for the feature overlay returns
// a text style for point features and the highlight
// style for other features (polygons in this case)
function styleFunction(feature, resolution) {
var style;
var geom = feature.getGeometry();
if (geom.getType() == 'Point') {
var text = feature.get('text');
baseTextStyle.text = text;
// this is inefficient as it could create new style objects for the
// same text.
// A good exercise to see if you understand would be to add caching
// of this text style
var isoCode = feature.get('isoCode').toLowerCase();
style = new ol.style.Style({
text: new ol.style.Text(baseTextStyle),
image: new ol.style.Icon({
src: '../assets/img/flags/'+isoCode+'.png'
}),
zIndex: 2
});
} else {
style = highlightStyle;
}
return [style];
}
var featureOverlay = new ol.FeatureOverlay({
map: map,
style: styleFunction
});
// when the mouse moves over the map, we get an event that we can use
// to create a new feature overlay from
map.on('pointermove', function(browserEvent) {
// first clear any existing features in the overlay
featureOverlay.getFeatures().clear();
var coordinate = browserEvent.coordinate;
var pixel = browserEvent.pixel;
// then for each feature at the mouse position ...
map.forEachFeatureAtPixel(pixel, function(feature, layer) {
// check the layer property, if it is not set then it means we
// are over an OverlayFeature and we can ignore this feature
if (!layer) {
return;
}
// test the feature's geometry type and compute a reasonable point
// at which to display the text.
var geometry = feature.getGeometry();
var point;
switch (geometry.getType()) {
case 'MultiPolygon':
var poly = geometry.getPolygons().reduce(function(left, right) {
return left.getArea() > right.getArea() ? left : right;
});
point = poly.getInteriorPoint().getCoordinates();
break;
case 'Polygon':
point = geometry.getInteriorPoint().getCoordinates();
break;
default:
point = geometry.getClosestPoint(coordinate);
}
// create a new feature to display the text
textFeature = new ol.Feature({
geometry: new ol.geom.Point(point),
text: feature.get('name'),
isoCode: feature.get('iso_a2').toLowerCase()
});
// and add it to the featureOverlay. Also add the feature itself
// so the country gets outlined
featureOverlay.addFeature(textFeature);
featureOverlay.addFeature(feature);
});
});
</script>
</body>
</html>
Using different projection codes
<!doctype html>
<html>
<head>
<title>WMS projection with WGS84</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<script src="../assets/ol3/js/ol.js"></script>
<script>
var blueMarbleLayer = new ol.layer.Tile({
source: new ol.source.TileWMS({
url: 'http://maps.boundlessgeo.com/geowebcache/service/wms',
params: {
'TILED' : true,
'VERSION': '1.1.1',
'LAYERS': 'bluemarble',
'FORMAT': 'image/jpeg'
}
})
});
var view = new ol.View({
projection: 'EPSG:4326',
center: [-1.81185, 52.443141],
zoom: 6
});
var map = new ol.Map({
target: 'map'
});
map.addLayer(blueMarbleLayer);
map.setView(view);
</script>
</body>
</html>
Using custom projection with WMS
sources
<!doctype html>
<html>
<head>
<title>WMS with custom projection</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<script src="../assets/proj4js/proj4.js"></script>
<script src="../assets/ol3/js/ol.js"></script>
<script>
proj4.defs("EPSG:2154","+proj=lcc +lat_1=49 +lat_2=44 +lat_0=46.5 +lon_0=3
+x_0=700000 +y_0=6600000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs");
var extent = [-378305.81, 6093283.21, 1212610.74, 7186901.68];
var projection = ol.proj.get('EPSG:2154');
projection.setExtent(extent);
var layers = [
new ol.layer.Image({
source: new ol.source.ImageWMS({
url: 'http://geoservices.brgm.fr/geologie',
attributions: [new ol.Attribution({
html: '© ' +
'BRGM (French USGS equivalent)'
})
],
params: {
'LAYERS': 'SCAN_F_GEOL1M',
'VERSION': '1.1.1'
},
extent: extent
})
})
];
var map = new ol.Map({
layers: layers,
target: 'map',
view: new ol.View({
projection: projection,
center: [755520.187986, 6587896.855407],
zoom: 2
})
});
</script>
</body>
</html>
Using custom projection without
Proj4js
<!doctype html>
<html>
<head>
<title>WMS with custom projection</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<script src="../assets/ol3/js/ol.js"></script>
<script>
var projection = new ol.proj.Projection({
code: 'EPSG:2154',
units: 'm'
});
var layers = [
new ol.layer.Image({
source: new ol.source.ImageWMS({
url: 'http://geoservices.brgm.fr/geologie',
attributions: [new ol.Attribution({
html: '© ' +
'BRGM (French USGS equivalent)'
})
],
params: {
'LAYERS': 'SCAN_F_GEOL1M',
'VERSION': '1.1.1'
}
})
})
];
var map = new ol.Map({
layers: layers,
target: 'map',
view: new ol.View({
projection: projection,
center: [755520.187986, 6587896.855407],
zoom: 6
})
});
</script>
</body>
</html>
Reprojecting geometries in vector
layers
<!doctype html>
<html>
<head>
<title>WFS reprojection </title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<script src="../assets/proj4js/proj4.js"></script>
<script src="../assets/ol3/js/ol.js"></script>
<script>
proj4.defs("EPSG:2154","+proj=lcc +lat_1=49 +lat_2=44 +lat_0=46.5 +lon_0=3
+x_0=700000 +y_0=6600000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs");
var extent = [-378305.81, 6093283.21, 1212610.74, 7186901.68];
var projection = ol.proj.get('EPSG:2154');
projection.setExtent(extent);
var countriesSource = new ol.source.GeoJSON({
projection: 'EPSG:2154',
url: '../assets/data/nutsv9_lea.geojson'
});
countriesSource.once('change', function(evt) {
if (this.getState() == 'ready') {
console.log(this.getFeatures()[0].getGeometry().getCoordinates());
console.log(this.getFeatures()
[0].getGeometry().clone().transform('EPSG:2154','EPSG:4326').getCoordinates());
}
});
var layers = [
new ol.layer.Image({
source: new ol.source.ImageWMS({
url: 'http://geoservices.brgm.fr/geologie',
attributions: [new ol.Attribution({
html: '© ' +
'BRGM (French USGS equivalent)'
})
],
params: {
'LAYERS': 'SCAN_F_GEOL1M',
'VERSION': '1.1.1'
},
extent: extent
})
}),
new ol.layer.Vector({
source: countriesSource
})
];
var map = new ol.Map({
layers: layers,
target: 'map',
view: new ol.View({
projection: projection,
center: [755520.187986, 6587896.855407],
zoom: 2
})
});
var bbox = new ol.layer.Vector({
source: new ol.source.GeoJSON()
});
map.addLayer(bbox);
var geojson = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {},
"geometry": {
"type": "Polygon",
"coordinates": [
[[-0.944824, 46.134170], [-0.944824, 48.312428],
[4.438477, 48.312428], [4.438477, 46.134170],
[-0.944824, 46.134170]
]
]
}
}
]
};
var format = new ol.format.GeoJSON({
defaultDataProjection: 'EPSG:4326'
});
var features = format.readFeatures(geojson, {
dataProjection: 'EPSG:4326',
featureProjection: 'EPSG:2154'
});
bbox.getSource().addFeatures(features);
</script>
</body>
</html>
Testing the use cases for
ol.interaction.Select
<!doctype html>
<html>
<head>
<title>Simple Select</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<script src="../assets/ol3/js/ol.js"></script>
<script>
var raster = new ol.layer.Tile({
source: new ol.source.MapQuest({layer: 'sat'})
});
var selectEuropa = new ol.style.Style({
stroke: new ol.style.Stroke({
color: '#ff0000',
width: 2
})
});
var defaultEuropa = new ol.style.Style({
stroke: new ol.style.Stroke({
color: '#0000ff',
width: 2
})
});
var vectorEuropa = new ol.layer.Vector({
id: 'europa',
source: new ol.source.GeoJSON({
projection: 'EPSG:3857',
url: '../assets/data/nutsv9_lea.geojson'
}),
style: defaultEuropa
});
var selectInteraction = new ol.interaction.Select({
condition: ol.events.condition.singleClick,
toggleCondition: ol.events.condition.shiftKeyOnly,
layers: function (layer) {
return layer.get('id') == 'europa';
},
style: selectEuropa
});
var london = ol.proj.transform([-0.12755, 51.507222], 'EPSG:4326',
'EPSG:3857');
var view = new ol.View({
center: london,
zoom: 6
});
var map = new ol.Map({
target: 'map'
});
map.addLayer(raster);
map.addLayer(vectorEuropa);
map.setView(view);
map.getInteractions().extend([selectInteraction]);
</script>
</body>
</html>
More options with
ol.interaction.Select
<!doctype html>
<html>
<head>
<title>Hello OpenStreetMap</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<script src="../assets/ol3/js/ol.js"></script>
<script>
var raster = new ol.layer.Tile({
source: new ol.source.MapQuest({layer: 'sat'})
});
var selectEuropa = new ol.style.Style({
stroke: new ol.style.Stroke({
color: '#ff0000',
width: 2
})
});
var defaultEuropa = new ol.style.Style({
stroke: new ol.style.Stroke({
color: '#0000ff',
width: 2
})
});
var vectorEuropa = new ol.layer.Vector({
id: 'europa',
source: new ol.source.GeoJSON({
projection: 'EPSG:3857',
url: '../assets/data/nutsv9_lea.geojson'
}),
style: defaultEuropa
});
var defaultFrancePoints = new ol.style.Style({
image: new ol.style.Circle({
fill: new ol.style.Fill({
color: 'blue'
}),
stroke: new ol.style.Stroke({
color: '#ffcc00'
}),
radius: 8
})
});
var selectFrancePoints = new ol.style.Style({
image: new ol.style.Circle({
fill: new ol.style.Fill({
color: '#ff0000'
}),
stroke: new ol.style.Stroke({
color: '#ffccff'
}),
radius: 16
})
});
var vectorFrancePoints = new ol.layer.Vector({
id: 'france',
source: new ol.source.GeoJSON({
projection: 'EPSG:3857',
url: '../assets/data/france_4326.geojson'
}),
style: defaultFrancePoints
});
var selectInteraction = new ol.interaction.Select({
layers: function(layer) {
return layer.get('selectable') == true;
},
style: [selectFrancePoints, selectEuropa]
});
var london = ol.proj.transform([-0.12755, 51.507222], 'EPSG:4326',
'EPSG:3857');
var view = new ol.View({
center: london,
zoom: 6
});
var map = new ol.Map({
target: 'map'
});
map.addLayer(raster);
map.addLayer(vectorEuropa);
map.addLayer(vectorFrancePoints);
map.setView(view);
map.getInteractions().extend([selectInteraction]);
vectorEuropa.set('selectable', true);
vectorFrancePoints.set('selectable', true);
</script>
</body>
</html>
Understanding
forEachFeatureAtPixel method
<!doctype html>
<html>
<head>
<title>Get Features from vector</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="information"></div>
<div id="map" class="map"></div>
<script src="../assets/ol3/js/ol-debug.js"></script>
<script>
var raster = new ol.layer.Tile({
source: new ol.source.MapQuest({layer: 'sat'})
});
var selectEuropa = new ol.style.Style({
stroke: new ol.style.Stroke({
color: '#ff0000',
width: 2
})
});
var defaultEuropa = new ol.style.Style({
stroke: new ol.style.Stroke({
color: '#0000ff',
width: 2
})
});
var vectorEuropa = new ol.layer.Vector({
id: 'europa',
source: new ol.source.GeoJSON({
projection: 'EPSG:3857',
url: '../assets/data/nutsv9_lea.geojson'
}),
style: defaultEuropa
});
var selectInteraction = new ol.interaction.Select({
layers: function (layer) {
return layer.get('id') == 'europa';
},
style: [selectEuropa]
});
var london = ol.proj.transform([-0.12755, 51.507222], 'EPSG:4326',
'EPSG:3857');
var view = new ol.View({
center: london,
zoom: 6
});
var map = new ol.Map({
target: 'map'
});
map.addLayer(raster);
map.addLayer(vectorEuropa);
map.setView(view);
map.getInteractions().extend([selectInteraction]);
var displayFeatureInfo = function(pixel) {
var features = [];
map.forEachFeatureAtPixel(pixel, function(feature, layer) {
features.push(feature);
});
var container = document.getElementById('information');
if (features.length > 0) {
var info = [];
for (var i = 0, ii = features.length; i < ii; ++i) {
info.push(features[i].get('N3NM'));
}
container.innerHTML = info.join(', ') || '(unknown)';
} else {
container.innerHTML = ' ';
}
};
map.on('click', function(evt) {
var pixel = evt.pixel;
displayFeatureInfo(pixel);
});
</script>
</body>
</html>
Understanding getGetFeatureInfoUrl method
<!doctype html>
<html>
<head>
<title>GetFeatureInfo</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="information"></div>
<div id="map" class="map"></div>
<script src="../assets/ol3/js/ol.js"></script>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
var wms_layer = new ol.layer.Tile({
source: new ol.source.TileWMS({
url: 'http://demo.boundlessgeo.com/geoserver/wms',
params: {'LAYERS': 'ne:ne'}
})
});
var view = new ol.View({
center: [0, 0],
zoom: 1
});
var map = new ol.Map({
layers: [wms_layer],
target: 'map',
view: view
});
var viewProjection = view.getProjection();
var viewResolution = view.getResolution();
var container = document.getElementById('information');
map.on('click', function(evt) {
var url = wms_layer.getSource().getGetFeatureInfoUrl(
evt.coordinate, viewResolution, viewProjection,
{'INFO_FORMAT': 'text/javascript',
'propertyName': 'formal_en'});
if (url) {
var parser = new ol.format.GeoJSON();
$.ajax({
url: url,
dataType: 'jsonp',
jsonpCallback: 'parseResponse'
}).then(function(response) {
var result = parser.readFeatures(response);
if (result.length) {
var info = [];
for (var i = 0, ii = result.length; i < ii; ++i) {
info.push(result[i].get('formal_en'));
}
container.innerHTML = info.join(', ');
} else {
container.innerHTML = ' ';
}
});
}
});
</script>
</body>
</html>
Introducing ol.Overlay with a static example
<!doctype html>
<html>
<head>
<title>Simple Overlay</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map">
<div id="popup"><b>OpenLayers 3 Code Sprint</b> <i>Humanities A3</i></div>
</div>
<script src="../assets/ol3/js/ol.js"></script>
<script>
var popup = new ol.Overlay({
element: document.getElementById('popup')
});
var osmLayer = new ol.layer.Tile({
source: new ol.source.OSM()
});
var ol3_sprint_location = ol.proj.transform([-1.20472, 52.93646], 'EPSG:4326',
'EPSG:3857');
var view = new ol.View({
center: ol3_sprint_location,
zoom: 16
});
var map = new ol.Map({
target: 'map'
});
map.addLayer(osmLayer);
map.setView(view);
map.addOverlay(popup);
popup.setPosition(ol3_sprint_location);
</script>
</body>
</html>
Using ol.Overlay dynamically with layers information
<!doctype html>
<html>
<head>
<title>Hello OpenStreetMap</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<body>
<div id="map" class="map">
<div id="popup"></div>
</div>
<script src="../assets/ol3/js/ol.js"></script>
<script>
var popup = new ol.Overlay({
element: document.getElementById('popup')
});
var osmLayer = new ol.layer.Tile({
source: new ol.source.OSM()
});
var selectEuropa = new ol.style.Style({
stroke: new ol.style.Stroke({
color: '#ff0000',
width: 2
})
});
var defaultEuropa = new ol.style.Style({
stroke: new ol.style.Stroke({
color: '#0000ff',
width: 2
})
});
var vectorEuropa = new ol.layer.Vector({
id: 'europa',
source: new ol.source.GeoJSON({
projection: 'EPSG:3857',
url: '../assets/data/nutsv9_lea.geojson'
}),
style: defaultEuropa
});
var selectInteraction = new ol.interaction.Select({
layers: function (layer) {
return layer.get('id') == 'europa';
}
});
var ol3_sprint_location = ol.proj.transform([-1.20472, 52.93646], 'EPSG:4326',
'EPSG:3857');
var view = new ol.View({
center: ol3_sprint_location,
zoom: 16
});
var map = new ol.Map({
target: 'map'
});
map.addLayer(osmLayer);
map.addLayer(vectorEuropa);
map.setView(view);
map.addOverlay(popup);
function pickRandomProperty() {
var prefix = ['bottom', 'center', 'top'];
var randPrefix = prefix[Math.floor(Math.random() * prefix.length)];
var suffix = ['left', 'center', 'right'];
var randSuffix = suffix[Math.floor(Math.random() * suffix.length)];
return randPrefix + '-' + randSuffix;
}
var container = document.getElementById('popup');
var displayFeatureInfo = function(pixel, coordinate) {
var features = [];
map.forEachFeatureAtPixel(pixel, function(feature, layer) {
features.push(feature);
});
if (features.length > 0) {
var info = [];
for (var i = 0, ii = features.length; i < ii; ++i) {
info.push(features[i].get('N3NM'));
}
container.innerHTML = info.join(', ') || '(unknown)';
var randomPositioning = pickRandomProperty();
popup.setPositioning(randomPositioning);
popup.setPosition(coordinate);
} else {
container.innerHTML = ' ';
}
};
map.on('click', function(evt) {
var coordinate = evt.coordinate;
displayFeatureInfo(evt.pixel, coordinate);
});
</script>
</body>
</html>
Using ol.interaction.Draw to share new information on the
Web
<!doctype html>
<html>
<head>
<title>Create new content</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map">
<div id="popup"></div>
</div>
<form class="form-inline">
<label>Geometry type </label>
<select id="type">
<option value="Point">Point</option>
<option value="LineString">LineString</option>
<option value="Polygon">Polygon</option>
</select>
</form>
<script src="../assets/ol3/js/ol.js"></script>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
var raster = new ol.layer.Tile({
source: new ol.source.MapQuest({layer: 'sat'})
});
var source = new ol.source.GeoJSON({
url: '/features.geojson'
});
var vector = new ol.layer.Vector({
id: 'vector',
source: source,
style: new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(255, 255, 255, 0.2)'
}),
stroke: new ol.style.Stroke({
color: '#ffcc33',
width: 2
}),
image: new ol.style.Circle({
radius: 7,
fill: new ol.style.Fill({
color: '#ffcc33'
})
})
})
});
var map = new ol.Map({
layers: [raster, vector],
target: 'map',
view: new ol.View({
center: [-11000000, 4600000],
zoom: 4
})
});
var typeSelect = document.getElementById('type');
var draw; // global so we can remove it later
function addInteraction() {
draw = new ol.interaction.Draw({
source: source,
type: typeSelect.value
});
map.addInteraction(draw);
draw.on('drawend',
function(evt) {
console.log(evt.feature);
var parser = new ol.format.GeoJSON();
var features = source.getFeatures();
var featuresGeoJSON = parser.writeFeatures(features);
$.ajax({
url: '/features.geojson',
type: 'POST',
data: featuresGeoJSON
}).then(function(response) {
console.log(response);
});
},
this);
}
typeSelect.onchange = function(e) {
map.removeInteraction(draw);
addInteraction();
};
addInteraction();
</script>
</body>
</html>
Using ol.interaction.Modify to update drawing
<!doctype html>
<html>
<head>
<title>Modify sample</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<script src="../assets/ol3/js/ol.js"></script>
<script>
var raster = new ol.layer.Tile({
source: new ol.source.MapQuest({layer: 'sat'})
});
var selectEuropa = new ol.style.Style({
stroke: new ol.style.Stroke({
color: '#ff0000',
width: 2
})
});
var defaultEuropa = new ol.style.Style({
stroke: new ol.style.Stroke({
color: '#0000ff',
width: 2
})
});
var vectorEuropa = new ol.layer.Vector({
id: 'europa',
source: new ol.source.GeoJSON({
projection: 'EPSG:3857',
url: '../assets/data/nutsv9_lea.geojson'
}),
style: defaultEuropa
});
var selectInteraction = new ol.interaction.Select({
condition: ol.events.condition.singleClick,
toggleCondition: ol.events.condition.shiftKeyOnly,
layers: function (layer) {
return layer.get('id') == 'europa';
},
style: selectEuropa
});
var modify = new ol.interaction.Modify({
features: selectInteraction.getFeatures()
});
var london = ol.proj.transform([-0.12755, 51.507222], 'EPSG:4326',
'EPSG:3857');
var view = new ol.View({
center: london,
zoom: 6
});
var map = new ol.Map({
target: 'map'
});
map.addLayer(raster);
map.addLayer(vectorEuropa);
map.setView(view);
map.getInteractions().extend([selectInteraction, modify]);
var selected_features = selectInteraction.getFeatures();
var dirty = {};
selected_features.on('add', function(evt) {
var feature = evt.element;
var fid = feature.getId();
feature.on('change', function(evt) {
dirty[evt.target.getId()] = true;
});
});
selected_features .on('remove', function(evt) {
var feature = evt.element;
var fid = feature.getId();
if (dirty[fid]) {
console.log('changed');
}
});
</script>
</body>
</html>
Configuring default interactions
<!doctype html>
<head>
<title>Simple example</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map" tabIndex="0"></div>
<script src="../assets/ol3/js/ol.js"></script>
<script>
var osm_default = new ol.layer.Tile({
source: new ol.source.OSM()
});
var map = new ol.Map({
layers: [osm_default],
interactions: ol.interaction.defaults({
keyboard: false,
altShiftDragRotate: false
}),
target: 'map',
view: new ol.View({
center: ol.proj.transform([-1.81185, 52.443141], 'EPSG:4326', 'EPSG:3857'),
zoom: 6
})
});
</script>
</body>
</html>
Using ol.interaction.DragRotateAndZoom
<!doctype html>
<head>
<title>Simple example</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<script src="../assets/ol3/js/ol-debug.js"></script>
<script>
var osm_default = new ol.layer.Tile({
source: new ol.source.OSM()
});
var map = new ol.Map({
layers: [osm_default],
interactions: ol.interaction.defaults({
shiftDragZoom: false
}).extend([new ol.interaction.DragRotateAndZoom()]),
target: 'map',
view: new ol.View({
center: ol.proj.transform([-1.81185, 52.443141], 'EPSG:4326', 'EPSG:3857'),
zoom: 6
})
});
</script>
</body>
</html>
Making rectangle export to GeoJSON with
ol.interaction.DragBox
<!doctype html>
<head>
<title>Simple example</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<script src="../assets/ol3/js/ol.js"></script>
<script>
var osm_default = new ol.layer.Tile({
source: new ol.source.OSM()
});
var dragBoxInteraction = new ol.interaction.DragBox({
condition: ol.events.condition.shiftKeyOnly,
style: new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'red',
width: 2
})
})
});
dragBoxInteraction.on('boxend', function(e) {
var format = new ol.format.GeoJSON();
var geom = e.target.getGeometry();
geom.transform('EPSG:3857', 'EPSG:4326');
var feature = new ol.Feature({
geometry: geom
});
var obj = format.writeFeatures([feature]);
console.log(JSON.stringify(obj));
});
var map = new ol.Map({
layers: [osm_default],
interactions: ol.interaction.defaults({
shiftDragZoom: false
}).extend([dragBoxInteraction]),
target: 'map',
view: new ol.View({
center: ol.proj.transform([-1.81185, 52.443141], 'EPSG:4326', 'EPSG:3857'),
zoom: 6
})
});
</script>
</body>
</html>
Starting with the default controls
<!doctype html>
<head>
<title>Simple example</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<script src="../assets/ol3/js/ol.js"></script>
<script>
var osm_default = new ol.layer.Tile({
source: new ol.source.OSM()
});
var map = new ol.Map({
layers: [osm_default],
controls: ol.control.defaults({
zoom: false,
attribution: false,
rotate: false
}),
target: 'map',
view: new ol.View({
center: ol.proj.transform([-1.81185, 52.443141], 'EPSG:4326', 'EPSG:3857'),
zoom: 6
})
});
</script>
</body>
</html>
Changing the default attribution styles
<!doctype html>
<html>
<head>
<title>Simple Select</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<br/>
<div id="myattribution"></div>
<script src="../assets/ol3/js/ol.js"></script>
<script>
var osm_default = new ol.layer.Tile({
source: new ol.source.OSM()
});
var map = new ol.Map({
layers: [osm_default],
logo: false,
controls: ol.control.defaults({
attributionOptions: {
target: document.getElementById('myattribution'),
className: 'myCustomClass'
}
}),
target: 'map',
view: new ol.View({
center: ol.proj.transform([-1.81185, 52.443141], 'EPSG:4326', 'EPSG:3857'),
zoom: 6
})
});
</script>
</body>
</html>
Finding your mouse position
<!doctype html>
<head>
<title>Simple example</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<br/>
<div id="myposition"></div>
<script src="../assets/ol3/js/ol.js"></script>
<script>
var osm_default = new ol.layer.Tile({
source: new ol.source.OSM()
});
var map = new ol.Map({
layers: [osm_default],
target: 'map',
view: new ol.View({
center: ol.proj.transform([-1.81185, 52.443141], 'EPSG:4326', 'EPSG:3857'),
zoom: 6
})
});
var mousePosition = new ol.control.MousePosition({
coordinateFormat: ol.coordinate.createStringXY(2),
projection: 'EPSG:4326',
target: document.getElementById('myposition'),
undefinedHTML: ' '
});
map.addControl(mousePosition);
</script>
</body>
</html>
Discovering ol.control.ScaleLine specific parameters
<!doctype html>
<html>
<head>
<title>Simple example</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<br/>
<div id="myposition"></div>
<script src="../assets/ol3/js/ol.js"></script>
<script>
var osm_default = new ol.layer.Tile({
source: new ol.source.OSM()
});
var map = new ol.Map({
layers: [osm_default],
target: 'map',
view: new ol.View({
center: ol.proj.transform([-1.8118500054456526, 52.4431409750608],
'EPSG:4326', 'EPSG:3857'),
zoom: 6
})
});
var mousePosition = new ol.control.ScaleLine({
units: 'degrees',
minWidth: 100
});
map.addControl(mousePosition);
</script>
</body>
</html>
Configuring ZoomToExtent and manipulate controls
<!doctype html>
<html>
<head>
<title>Simple example</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<script src="../assets/ol3/js/ol.js"></script>
<script>
var zoomToExtentControl = new ol.control.ZoomToExtent({
extent: [-11243808.051695308, 4406397.202710291, -4561377.290892059,
6852382.107835932]
});
var osm_default = new ol.layer.Tile({
source: new ol.source.OSM()
});
var map = new ol.Map({
layers: [osm_default],
target: 'map',
view: new ol.View({
center: ol.proj.transform([-83.43924243777822, 60.16139104246781],
'EPSG:4326', 'EPSG:3857'),
zoom: 3
})
});
map.addControl(zoomToExtentControl);
var controls = map.getControls();
var attributionControl;
controls.forEach(function (el) {
console.log(el instanceof ol.control.Attribution);
if (el instanceof ol.control.Attribution) {
attributionControl = el;
}
});
map.removeControl(attributionControl);
</script>
</body>
</html>
Extending ol.control.Control to make your own control
<!doctype html>
<html>
<head>
<title>Custom control</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map">
</div>
<form class="form-inline">
<label>Geometry type </label>
<select id="type">
<option value="Point">Point</option>
<option value="LineString">LineString</option>
<option value="Polygon">Polygon</option>
</select>
</form>
<script src="../assets/ol3/js/ol.js"></script>
<script src="../assets/js/FileSaver.js"></script>
<script>
function download(filename, text) {
var blob = new Blob([text], {type: "application/json;charset=utf-8"});
saveAs(blob, filename);
}
window.app = {};
var app = window.app;
/**
* @constructor
* @extends {ol.control.Control}
* @param {Object=} opt_options Control options.
*/
app.generateGeoJSONControl = function(opt_options) {
var options = opt_options || {};
var anchor = document.createElement('a');
anchor.href = '#export-geojson';
anchor.innerHTML = 'G';
var this_ = this;
var getGeoJSON = function(e) {
// prevent #export-geojson anchor from getting appended to the url
e.preventDefault();
var source = options.source;
var format = new ol.format.GeoJSON();
var features = source.getFeatures();
var featuresGeoJSON = format.writeFeatures(features);
download('export.geojson', JSON.stringify(featuresGeoJSON));
};
anchor.addEventListener('click', getGeoJSON, false);
anchor.addEventListener('touchstart', getGeoJSON, false);
var element = document.createElement('div');
element.className = 'export-geojson ol-unselectable';
element.appendChild(anchor);
ol.control.Control.call(this, {
element: element,
target: options.target
});
};
ol.inherits(app.generateGeoJSONControl, ol.control.Control);
var raster = new ol.layer.Tile({
source: new ol.source.MapQuest({layer: 'sat'})
});
var source = new ol.source.GeoJSON({
url: '/features.geojson'
});
var vector = new ol.layer.Vector({
id: 'vector',
source: source,
style: new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(255, 255, 255, 0.2)'
}),
stroke: new ol.style.Stroke({
color: '#ffcc33',
width: 2
}),
image: new ol.style.Circle({
radius: 7,
fill: new ol.style.Fill({
color: '#ffcc33'
})
})
})
});
var map = new ol.Map({
layers: [raster, vector],
controls: ol.control.defaults().extend([
new app.generateGeoJSONControl({source: source})
]),
target: 'map',
view: new ol.View({
center: [-11000000, 4600000],
zoom: 4
})
});
var typeSelect = document.getElementById('type');
var draw;
function addInteraction() {
draw = new ol.interaction.Draw({
source: source,
type: typeSelect.value
});
map.addInteraction(draw);
}
typeSelect.onchange = function(e) {
map.removeInteraction(draw);
addInteraction();
};
addInteraction();
</script>
</body>
</html>
Go mobile!
<!doctype html>
<html>
<head>
<title>Mobile Examples</title>
<!-- the viewport is important for mobile devices -->
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-
scale=1.0, user-scalable=no">
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="full-map"></div>
<script src="../assets/ol3/js/ol.js"></script>
<script>
// other than adding the <meta> viewport above, our normal setup will
// work fine for mobile
var layer = new ol.layer.Tile({
source: new ol.source.OSM()
});
var london = ol.proj.transform([-0.12755, 51.507222], 'EPSG:4326',
'EPSG:3857');
var view = new ol.View({
center: london,
zoom: 6
});
var map = new ol.Map({
target: 'map',
layers: [layer],
view: view
});
</script>
</body>
</html>
Location
<!doctype html>
<html>
<head>
<title>Map Examples</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-
scale=1.0, user-scalable=no">
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
<!-- font-awesome is an iconic font, which means we can draw resolution-
independent icons -->
<link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css"
rel="stylesheet">
</head>
<body>
<div id="map" class="full-map"></div>
<div id="location" class="marker"><span class="icon-flag"></div>
<script src="../assets/ol3/js/ol-debug.js"></script>
<script>
var layer = new ol.layer.Tile({
source: new ol.source.OSM()
});
var london = ol.proj.transform([-0.12755, 51.507222], 'EPSG:4326',
'EPSG:3857');
var view = new ol.View({
center: london,
zoom: 6
});
var map = new ol.Map({
target: 'map',
layers: [layer],
view: view
});
// create an Overlay using the div with id location.
var marker = new ol.Overlay({
element: document.getElementById('location'),
positioning: 'bottom-left',
stopEvent: false
});
// add it to the map
map.addOverlay(marker);
// create a Geolocation object setup to track the position of the device
var geolocation = new ol.Geolocation({
tracking: true
});
// bind the projection to the view so that positions are reported in the
// projection of the view
geolocation.bindTo('projection', view);
// bind the marker's position to the geolocation object, the marker will
// move automatically when the GeoLocation API provides position updates
marker.bindTo('position', geolocation);
// when the GeoLocation API provides a position update, center the view
// on the new position
geolocation.on('change:position', function() {
var p = geolocation.getPosition();
console.log(p[0] + ' : ' + p[1]);
view.setCenter([parseFloat(p[0]), parseFloat(p[1])]);
});
</script>
</body>
</html>
A sense of direction
<!doctype html>
<html>
<head>
<title>Map Examples</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-
scale=1.0, user-scalable=no">
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
<link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css"
rel="stylesheet">
</head>
<body>
<div id="map" class="full-map"></div>
<div id="location" class="marker"><span class="icon-arrow-up"></span></div>
<script src="../assets/ol3/js/ol-debug.js"></script>
<script>
var layer = new ol.layer.Tile({
source: new ol.source.OSM()
});
var london = ol.proj.transform([-0.12755, 51.507222], 'EPSG:4326',
'EPSG:3857');
var view = new ol.View({
center: london,
zoom: 6
});
var map = new ol.Map({
target: 'map',
layers: [layer],
view: view
});
// set up geolocation to track our position
var geolocation = new ol.Geolocation({
tracking: true
});
// bind it to the view's projection and update the view as we move
geolocation.bindTo('projection', view);
geolocation.on('change:position', function() {
view.setCenter(geolocation.getPosition());
});
// add a marker to display the current location
var marker = new ol.Overlay({
element: document.getElementById('location'),
positioning: 'center-center'
});
map.addOverlay(marker);
// and bind it to the geolocation's position updates
marker.bindTo('position', geolocation);
// create a new device orientation object set to track the device
var deviceOrientation = new ol.DeviceOrientation({
tracking: true
});
// when the device changes heading, rotate the view so that
// 'up' on the device points the direction we are facing
deviceOrientation.on('change:heading', onChangeHeading);
function onChangeHeading(event) {
var heading = event.target.getHeading();
view.setRotation(-heading);
}
</script>
</body>
</html>
Track me
<!doctype html>
<html>
<head>
<title>Map Examples</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-
scale=1.0, user-scalable=no">
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
<link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css"
rel="stylesheet">
</head>
<body>
<div id="map" class="full-map"></div>
<div id="location" class="marker"><span class="icon-arrow-up"></span></div>
<script src="../assets/ol3/js/ol-debug.js"></script>
<script>
// create a style to display our position history (track)
var trackStyle = new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'rgba(0,0,255,1.0)',
width: 3,
lineCap: 'round'
})
});
// use a single feature with a linestring geometry to display our track
var trackFeature = new ol.Feature({
geometry: new ol.geom.LineString([])
});
// we'll need a vector layer to render it
var trackLayer = new ol.layer.Vector({
source: new ol.source.Vector({
features: [trackFeature]
}),
style: trackStyle
});
var baseLayer = new ol.layer.Tile({
source: new ol.source.OSM()
});
var london = ol.proj.transform([-0.12755, 51.507222], 'EPSG:4326',
'EPSG:3857');
var view = new ol.View({
center: london,
zoom: 6
});
var map = new ol.Map({
target: 'map',
layers: [baseLayer, trackLayer],
view: view
});
// set up the geolocation api to track our position
var geolocation = new ol.Geolocation({
tracking: true
});
// bind the view's projection
geolocation.bindTo('projection', view);
// when we get a position update, add the coordinate to the track's
// geometry and recenter the view
geolocation.on('change:position', function() {
var coordinate = geolocation.getPosition();
view.setCenter(coordinate);
trackFeature.getGeometry().appendCoordinate(coordinate);
});
// put a marker at our current position
var marker = new ol.Overlay({
element: document.getElementById('location'),
positioning: 'center-center'
});
map.addOverlay(marker);
marker.bindTo('position', geolocation);
// rotate the view to match the device orientation
var deviceOrientation = new ol.DeviceOrientation({
tracking: true
});
deviceOrientation.on('change:heading', onChangeHeading);
function onChangeHeading(event) {
var heading = event.target.getHeading();
view.setRotation(-heading);
}
</script>
</body>
</html>
Chapter 11, Creating Web Map Apps
Adding data to your map
<!doctype html>
<html>
<head>
<title>Flickr Search</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<script src="../assets/ol3/js/ol-debug.js"></script>
<script>
// the source of our photos is a KML file
var flickrSource = new ol.source.KML({
url: '../assets/data/flickr_data.kml',
projection: 'EPSG:3857'
});
// the vector layer uses the source
var flickrLayer = new ol.layer.Vector({
source: flickrSource
});
// a tile layer as a base map to provide context
var layer = new ol.layer.Tile({
source: new ol.source.OSM()
});
// center on 0,0 and transform for the view's projection
var center = ol.proj.transform([0,0], 'EPSG:4326', 'EPSG:3857');
// a suitable starting point for the map's view
var view = new ol.View({
center: center,
zoom: 1
});
// the map goes in the map div
var map = new ol.Map({
target: 'map',
layers: [layer, flickrLayer],
view: view
});
</script>
</body>
</html>
Creating a style function
<!doctype html>
<html>
<head>
<title>Flickr Search</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="../assets/ol3/js/ol-debug.js"></script>
<script>
// the source of our photos is a KML file
var flickrSource = new ol.source.KML({
url: '../assets/data/flickr_data.kml',
projection: 'EPSG:3857',
extractStyles: false
});
// use a style function to replace the styles in the KML file
// this is a placeholder for now
function flickrStyle(feature) {
var style = new ol.style.Style({
image: new ol.style.Circle({
radius: 6,
stroke: new ol.style.Stroke({
color: 'white',
width: 2
}),
fill: new ol.style.Fill({
color: 'green'
})
})
});
return [style];
}
var flickrLayer = new ol.layer.Vector({
source: flickrSource,
style: flickrStyle
});
var layer = new ol.layer.Tile({
source: new ol.source.OSM()
});
var center = ol.proj.transform([0, 0], 'EPSG:4326', 'EPSG:3857');
var view = new ol.View({
center: center,
zoom: 2
});
var map = new ol.Map({
target: 'map',
layers: [layer, flickrLayer],
view: view
});
</script>
</body>
</html>
Switching to JSON data
<!doctype html>
<html>
<head>
<title>Flickr Search</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="../assets/ol3/js/ol-debug.js"></script>
<script>
// everything is the same as the previous sample, except at the end
// we load data from a JSON file instead of KML
var flickrSource = new ol.source.Vector();
function flickrStyle(feature) {
var style = new ol.style.Style({
image: new ol.style.Circle({
radius: 6,
stroke: new ol.style.Stroke({
color: 'white',
width: 2
}),
fill: new ol.style.Fill({
color: 'green'
})
})
});
return [style];
}
var flickrLayer = new ol.layer.Vector({
source: flickrSource,
style: flickrStyle
});
var layer = new ol.layer.Tile({
source: new ol.source.OSM()
});
var center = ol.proj.transform([0,0], 'EPSG:4326', 'EPSG:3857');
var view = new ol.View({
center: center,
zoom: 2
});
var map = new ol.Map({
target: 'map',
layers: [layer, flickrLayer],
view: view
});
// when jQuery has loaded the data, we can create features for each photo
function successHandler(data) {
// we need to transform the geometries into the view's projection
var transform = ol.proj.getTransform('EPSG:4326', 'EPSG:3857');
// loop over the items in the response
data.items.forEach(function(item) {
// create a new feature with the item as the properties
var feature = new ol.Feature(item);
// add a url property for later ease of access
feature.set('url', item.media.m);
// create an appropriate geometry and add it to the feature
var coordinate = transform([parseFloat(item.longitude),
parseFloat(item.latitude)]);
var geometry = new ol.geom.Point(coordinate);
feature.setGeometry(geometry);
// add the feature to the source
flickrSource.addFeature(feature);
});
}
$.ajax({
url: '../assets/data/flickr_data.json',
dataType: 'jsonp',
jsonpCallback: 'jsonFlickrFeed',
success: successHandler
});
</script>
</body>
</html>
Creating a thumbnail style
<!doctype html>
<html>
<head>
<title>Flickr Search</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="../assets/ol3/js/ol-debug.js"></script>
<script>
var flickrSource = new ol.source.Vector();
// a cache for the style objects, always good practice
var cache = {};
function flickrStyle(feature) {
// cache styles by photo url
var url = feature.get('url');
if (!cache[url]) {
// use the icon style and scale the image to 10% so its not too large
cache[url] = new ol.style.Style({
image: new ol.style.Icon({
scale: 0.10,
src: url
})
});
}
return [cache[url]];
}
var flickrLayer = new ol.layer.Vector({
source: flickrSource,
style: flickrStyle
});
var layer = new ol.layer.Tile({
source: new ol.source.OSM()
});
var center = ol.proj.transform([0,0], 'EPSG:4326', 'EPSG:3857');
var view = new ol.View({
center: center,
zoom: 2
});
var map = new ol.Map({
target: 'map',
layers: [layer, flickrLayer],
view: view
});
function successHandler(data) {
var transform = ol.proj.getTransform('EPSG:4326', 'EPSG:3857');
data.items.forEach(function(item) {
var feature = new ol.Feature(item);
feature.set('url', item.media.m);
var coordinate = transform([parseFloat(item.longitude),
parseFloat(item.latitude)]);
var geometry = new ol.geom.Point(coordinate);
feature.setGeometry(geometry);
flickrSource.addFeature(feature);
});
}
$.ajax({
url: '../assets/data/flickr_data.json',
dataType: 'jsonp',
jsonpCallback: 'jsonFlickrFeed',
success: successHandler
});
</script>
</body>
</html>
Adding the select interaction
<!doctype html>
<html>
<head>
<title>Flickr Search</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="../assets/ol3/js/ol-debug.js"></script>
<script>
var vectorSource = new ol.source.KML({
url: '../assets/data/flickr_data.kml',
projection: 'EPSG:3857'
});
// a cluster source can group photos that are too close
var clusterSource = new ol.source.Cluster({
source: vectorSource,
distance: 40
});
var cache = {};
// this function computes a circle style
// based on the size of a cluster
// the style is cached.
function getCircleStyle(size) {
var key = 'circle' + size;
if (!cache[key]) {
cache[key] = new ol.style.Style({
image: new ol.style.Circle({
radius: 8 + size,
fill: new ol.style.Fill({
color: 'rgb(97, 151, 255)'
}),
stroke: new ol.style.Stroke({
color: 'white',
width: 2
})
})
});
}
return cache[key];
}
// this function computes a text style
// based on the size of a cluster
// the style is cached
function getTextStyle(text) {
var key = 'text' + text;
if (!cache[key]) {
cache[key] = new ol.style.Style({
text: new ol.style.Text({
font: '10px sans-serif',
text: text,
textBaseline: 'alphabetic',
offsetY: 4,
fill: new ol.style.Fill({
color: 'white'
})
})
});
}
return cache[key];
}
// the style function for the cluster layer combines
// a circle and a text style based on the size of the cluster
function clusterStyle(feature, resolution) {
var size = feature.get('features').length;
var pointStyle = getCircleStyle(size);
var textStyle = getTextStyle(size.toString());
return [pointStyle, textStyle];
}
var vectorLayer = new ol.layer.Vector({
source: clusterSource,
style: clusterStyle
});
var layer = new ol.layer.Tile({
source: new ol.source.OSM()
});
var center = ol.proj.transform([0,0], 'EPSG:4326', 'EPSG:3857');
var view = new ol.View({
center: center,
zoom: 2
});
var map = new ol.Map({
target: 'map',
layers: [layer, vectorLayer],
view: view
});
var select = new ol.interaction.Select({
layers: [vectorLayer]
});
map.addInteraction(select);
</script>
</body>
</html>
Handling selection events
<!doctype html>
<html>
<head>
<title>Flickr Search</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<div id="photo-info"></div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="../assets/ol3/js/ol-debug.js"></script>
<script>
var flickrSource = new ol.source.Vector();
var cache = {};
function photoStyle(feature, scale) {
var url = feature.get('url');
var key = scale + url;
if (!cache[key]) {
cache[key] = new ol.style.Style({
image: new ol.style.Icon({
scale: scale,
src: url
})
});
}
return cache[key];
}
function flickrStyle(feature) {
return [photoStyle(feature, 0.10)];
}
function selectedStyle(feature) {
return [photoStyle(feature, 0.50)];
}
var flickrLayer = new ol.layer.Vector({
source: flickrSource,
style: flickrStyle
});
var layer = new ol.layer.Tile({
source: new ol.source.OSM()
});
var center = ol.proj.transform([0,0], 'EPSG:4326', 'EPSG:3857');
var view = new ol.View({
center: center,
zoom: 2
});
var map = new ol.Map({
target: 'map',
layers: [layer, flickrLayer],
view: view
});
// create a Select interaction and add it to the map
var select = new ol.interaction.Select({
layers: [flickrLayer],
style: selectedStyle
});
map.addInteraction(select);
// use the features Collection to detect when a feature is selected,
// the collection will emit the add event
var selectedFeatures = select.getFeatures();
selectedFeatures.on('add', function(event) {
var feature = event.target.item(0);
var url = feature.get('url');
// put the url of the feature into the photo-info div
$('#photo-info').html(url);
});
// when a feature is removed, clear the photo-info div
selectedFeatures.on('remove', function(event) {
$('#photo-info').empty();
});
function successHandler(data) {
var transform = ol.proj.getTransform('EPSG:4326', 'EPSG:3857');
data.items.forEach(function(item) {
var feature = new ol.Feature(item);
feature.set('url', item.media.m);
var coordinate = transform([parseFloat(item.longitude),
parseFloat(item.latitude)]);
var geometry = new ol.geom.Point(coordinate);
feature.setGeometry(geometry);
flickrSource.addFeature(feature);
});
}
$.ajax({
url: '../assets/data/flickr_data.json',
dataType: 'jsonp',
jsonpCallback: 'jsonFlickrFeed',
success: successHandler
});
</script>
</body>
</html>
Displaying photo information
<!doctype html>
<html>
<head>
<title>Flickr Search</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<div id="photo-info"></div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="../assets/ol3/js/ol-debug.js"></script>
<script>
var flickrSource = new ol.source.Vector();
var cache = {};
function photoStyle(feature, scale) {
var url = feature.get('url');
var key = scale + url;
if (!cache[key]) {
cache[key] = new ol.style.Style({
image: new ol.style.Icon({
scale: scale,
src: url
})
});
}
return cache[key];
}
function flickrStyle(feature) {
return [photoStyle(feature, 0.10)];
}
function selectedStyle(feature) {
return [photoStyle(feature, 0.50)];
}
var flickrLayer = new ol.layer.Vector({
source: flickrSource,
style: flickrStyle
});
var layer = new ol.layer.Tile({
source: new ol.source.OSM()
});
var center = ol.proj.transform([0,0], 'EPSG:4326', 'EPSG:3857');
var view = new ol.View({
center: center,
zoom: 2
});
var map = new ol.Map({
target: 'map',
layers: [layer, flickrLayer],
view: view
});
// a simple templating function that replaces keywords wrapped in
// curly brackets with the equivalent value from the feature properties
function photoContent(feature) {
// get the HTML content of the template as a string
var content = $('#photo-template').html();
// a list of keys we will consider for replacement
var keys =
['author','author_id','date_taken','latitude','longitude','link','url','tags','title'
];
for (var i=0; i<keys.length; i++) {
var key = keys[i];
// get the value of the key
var value = feature.get(key);
// and replace its template placeholder in the content. If the template
// placeholder is absent, nothing happens so its safe
content = content.replace('{'+key+'}',value);
}
return content;
}
var select = new ol.interaction.Select({
layers: [flickrLayer],
style: selectedStyle
});
map.addInteraction(select);
var selectedFeatures = select.getFeatures();
selectedFeatures.on('add', function(event) {
var feature = event.target.item(0);
// instead of the photo url, get the templated content
// for the current feature instead
var content = photoContent(feature);
$('#photo-info').html(content);
});
selectedFeatures.on('remove', function(event) {
$('#photo-info').empty();
});
function successHandler(data) {
var transform = ol.proj.getTransform('EPSG:4326', 'EPSG:3857');
data.items.forEach(function(item) {
var feature = new ol.Feature(item);
feature.set('url', item.media.m);
var coordinate = transform([parseFloat(item.longitude),
parseFloat(item.latitude)]);
var geometry = new ol.geom.Point(coordinate);
feature.setGeometry(geometry);
flickrSource.addFeature(feature);
});
}
$.ajax({
url: '../assets/data/flickr_data.json',
dataType: 'jsonp',
jsonpCallback: 'jsonFlickrFeed',
success: successHandler
});
</script>
<!-- script tags are ignored for rendering, and adding type="text/html"
to the script tag makes the javascript engine ignore it, but
we can still access it as a DOM element and get its formatted content -->
<script type="text/html" id="photo-template">
<a href="{link}" target="_blank" title="Click to open photo in new tab"><img
src="{url}" style="float: left"></a><br>
<p>Taken by <a href="http://www.flickr.com/people/{author_id}" target="_blank"
title="Click to view author details in new tab">{author}</a> on {date_taken} at lat:
{latitude} lon: {longitude}</p><br>
<p>Tagged in <b>{tags}</b></p>
</script>
</body>
</html>
Getting dynamic data
<!doctype html>
<html>
<head>
<title>Flickr Search</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<div id="photo-info"></div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="../assets/ol3/js/ol-debug.js"></script>
<script>
var flickrSource = new ol.source.Vector();
var cache = {};
function photoStyle(feature, scale) {
var url = feature.get('url');
var key = scale + url;
if (!cache[key]) {
cache[key] = new ol.style.Style({
image: new ol.style.Icon({
scale: scale,
src: url
})
});
}
return cache[key];
}
function flickrStyle(feature) {
return [photoStyle(feature, 0.10)];
}
function selectedStyle(feature) {
return [photoStyle(feature, 0.50)];
}
var flickrLayer = new ol.layer.Vector({
source: flickrSource,
style: flickrStyle
});
var layer = new ol.layer.Tile({
source: new ol.source.OSM()
});
var center = ol.proj.transform([0,0], 'EPSG:4326', 'EPSG:3857');
var view = new ol.View({
center: center,
zoom: 2
});
var map = new ol.Map({
renderer: 'canvas',
target: 'map',
layers: [layer, flickrLayer],
view: view
});
function photoContent(feature) {
var content = $('#photo-template').html();
var keys =
['author','author_id','date_taken','latitude','longitude','link','url','tags','title'
];
for (var i=0; i<keys.length; i++) {
var key = keys[i];
var value = feature.get(key);
content = content.replace('{'+key+'}',value);
}
return content;
}
var select = new ol.interaction.Select({
layers: [flickrLayer],
style: selectedStyle
});
map.addInteraction(select);
var selectedFeatures = select.getFeatures();
selectedFeatures.on('add', function(event) {
var feature = event.target.item(0);
var content = photoContent(feature);
$('#photo-info').html(content);
});
selectedFeatures.on('remove', function(event) {
$('#photo-info').empty();
});
function successHandler(data) {
var transform = ol.proj.getTransform('EPSG:4326', 'EPSG:3857');
data.items.forEach(function(item) {
var feature = new ol.Feature(item);
feature.set('url', item.media.m);
var coordinate = transform([parseFloat(item.longitude),
parseFloat(item.latitude)]);
var geometry = new ol.geom.Point(coordinate);
feature.setGeometry(geometry);
flickrSource.addFeature(feature);
});
}
// the only change is to point at the remote URL for the feed
$.ajax({
url: 'http://api.flickr.com/services/feeds/geo/?format=json&tags=bird',
dataType: 'jsonp',
jsonpCallback: 'jsonFlickrFeed',
success: successHandler
});
</script>
<script type="text/html" id="photo-template">
<a href="{link}" target="_blank" title="Click to open photo in new tab"><img
src="{url}" style="float: left"></a><br>
<p>Taken by <a href="http://www.flickr.com/people/{author_id}" target="_blank"
title="Click to view author details in new tab">{author}</a> on {date_taken} at lat:
{latitude} lon: {longitude}</p><br>
<p>Tagged in <b>{tags}</b></p>
</script>
</body>
</html>
Adding dynamic tags to your map
<!doctype html>
<html>
<head>
<title>Flickr Search</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<div id="search" style="position: absolute; top: 10px; right: 10px; padding: 5px;
background-color: rgba(255,255,255,0.5);">
<input type="text" placeholder="Search photos by tag(s)" style="width: 200px">
<button type="button">Search</button>
</div>
<div id="photo-info"></div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="../assets/ol3/js/ol.js"></script>
<script>
var flickrSource = new ol.source.Vector();
var cache = {};
function photoStyle(feature, scale) {
var url = feature.get('url');
var key = scale + url;
if (!cache[key]) {
cache[key] = new ol.style.Style({
image: new ol.style.Icon({
scale: scale,
src: url
})
});
}
return cache[key];
}
function flickrStyle(feature) {
return [photoStyle(feature, 0.10)];
}
function selectedStyle(feature) {
return [photoStyle(feature, 0.50)];
}
var flickrLayer = new ol.layer.Vector({
source: flickrSource,
style: flickrStyle
});
var layer = new ol.layer.Tile({
source: new ol.source.OSM()
});
var center = ol.proj.transform([0,0], 'EPSG:4326', 'EPSG:3857');
var view = new ol.View({
center: center,
zoom: 2
});
var map = new ol.Map({
renderer: 'canvas',
target: 'map',
layers: [layer, flickrLayer],
view: view
});
function photoContent(feature) {
var content = $('#photo-template').html();
var keys =
['author','author_id','date_taken','latitude','longitude','link','url','tags','title'
];
for (var i=0; i<keys.length; i++) {
var key = keys[i];
var value = feature.get(key);
content = content.replace('{'+key+'}',value);
}
return content;
}
var select = new ol.interaction.Select({
layers: [flickrLayer],
style: selectedStyle
});
map.addInteraction(select);
var selectedFeatures = select.getFeatures();
selectedFeatures.on('add', function(event) {
var feature = event.target.item(0);
var content = photoContent(feature);
$('#photo-info').html(content);
});
selectedFeatures.on('remove', function(event) {
$('#photo-info').empty();
});
function successHandler(data) {
var transform = ol.proj.getTransform('EPSG:4326', 'EPSG:3857');
data.items.forEach(function(item) {
var feature = new ol.Feature(item);
feature.set('url', item.media.m);
var coordinate = transform([parseFloat(item.longitude),
parseFloat(item.latitude)]);
var geometry = new ol.geom.Point(coordinate);
feature.setGeometry(geometry);
flickrSource.addFeature(feature);
});
}
// by moving the data loading into a function, we can call it with the user's
// search term and construct a new URL getting photos for the relevant tags.
// we can also clear existing features and selected features.
function loadFlickrFeed(tags) {
selectedFeatures.clear();
flickrSource.clear();
$('#photo-info').empty();
$.ajax({
url: 'http://api.flickr.com/services/feeds/geo',
data: {
format: 'json',
tags: tags
},
dataType: 'jsonp',
jsonpCallback: 'jsonFlickrFeed',
success: successHandler
});
}
// use jQuery to handle the user clicking the search button
$(document).on('click', '#search button', function() {
var value = $('#search input').val();
var tags = value.split(' ').join(',');
loadFlickrFeed(tags);
});
</script>
<script type="text/html" id="photo-template">
<a href="{link}" target="_blank" title="Click to open photo in new tab"><img
src="{url}" style="float: left"></a><br>
<p>Taken by <a href="http://www.flickr.com/people/{author_id}" target="_blank"
title="Click to view author details in new tab">{author}</a> on {date_taken} at lat:
{latitude} lon: {longitude}</p><br>
<p>Tagged in <b>{tags}</b></p>
</script>
</body>
</html>
Creating a combined build
<!doctype html>
<html>
<head>
<title>Flickr Search</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<div id="search" style="position: absolute; top: 10px; right: 10px; padding: 5px;
background-color: rgba(255,255,255,0.5);">
<input type="text" placeholder="Search photos by tag(s)" style="width: 200px">
<button type="button">Search</button>
</div>
<div id="photo-info"></div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<!-- this replaces both ol.js and our application javascript as they are compiled
into a single file -->
<script src="flickr_combined.built.js"></script>
<script type="text/html" id="photo-template">
<a href="{link}" target="_blank" title="Click to open photo in new tab"><img
src="{url}" style="float: left"></a><br>
<p>Taken by <a href="http://www.flickr.com/people/{author_id}" target="_blank"
title="Click to view author details in new tab">{author}</a> on {date_taken} at lat:
{latitude} lon: {longitude}</p><br>
<p>Tagged in <b>{tags}</b></p>
</script>
</body>
</html>
Creating a separate build
<!doctype html>
<html>
<head>
<title>Flickr Search</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<div id="search" style="position: absolute; top: 10px; right: 10px; padding: 5px;
background-color: rgba(255,255,255,0.5);">
<input type="text" placeholder="Search photos by tag(s)" style="width: 200px">
<button type="button">Search</button>
</div>
<div id="photo-info"></div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<!-- we need to load both our custom build of the OpenLayers library and our
application code -->
<script src="flickr_separate.ol.js"></script>
<script src="flickr_separate.js"></script>
<script type="text/html" id="photo-template">
<a href="{link}" target="_blank" title="Click to open photo in new tab"><img
src="{url}" style="float: left"></a><br>
<p>Taken by <a href="http://www.flickr.com/people/{author_id}" target="_blank"
title="Click to view author details in new tab">{author}</a> on {date_taken} at lat:
{latitude} lon: {longitude}</p><br>
<p>Tagged in <b>{tags}</b></p>
</script>
</body>
</html>
Situsnya
https://openlayersbook.github.io/appendix-c-squashing-bugs-with-
web-debuggers/intro.html