Draw and add marker OpenLayers
by Dan Daniel
HTML
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ol3/3.5.0/ol.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/ol3/3.5.0/ol.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<div id="map" class="map" tabindex="0"></div>
CSS
.contextMenu {
cursor: pointer;
background-color: #eee;
position: absolute;
border: solid 1px black;
width: 150px;
}
.contextMenu .menuItem {
padding: 5px;
}
.contextMenu .menuItem:hover {
background-color: #ccc;
}
.menuSeparator {
border-bottom: solid 1px black;
}
JavaScript
var vectorSource = new ol.source.Vector();
var vectorLayer = new ol.layer.Vector({
source: vectorSource
});
var features = new ol.Collection();
var areaSource = new ol.source.Vector({
features: features
});
var areaVectorLayer = new ol.layer.Vector({
source: areaSource,
style: new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(255, 167, 66, 0.4)'
}),
stroke: new ol.style.Stroke({
color: '#ff7733',
width: 2
}),
image: new ol.style.Circle({
radius: 7,
fill: new ol.style.Fill({
color: '#ff7733'
})
})
})
});
var iconStyle = new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 46],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
opacity: 0.75,
src: '//openlayers.org/en/v3.8.2/examples/data/icon.png'
})
});
var map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
vectorLayer,
areaVectorLayer],
target: 'map',
controls: ol.control.defaults({
attributionOptions: /** @type {olx.control.AttributionOptions} */
({
collapsible: false
})
}),
view: new ol.View({
center: [0, 0],
zoom: 2
})
});
map.on('click', function (evt) {
$('.contextMenu').hide();
});
map.getViewport().addEventListener('contextmenu', function (e) {
e.preventDefault();
openContextMenu(e.x, e.y);
});
function openContextMenu(x, y) {
$('.contextMenu').remove();
$('body').append('<div class="contextMenu" style=" top: ' + y + 'px; left:' + x + 'px;">' +
'<div class="menuItem" onclick="handleContexMenuEvent(\'zoomIn\', \''+ x +'\', \''+ y +'\');"> Zoom In </div>' +
'<div class="menuItem" onclick="handleContexMenuEvent(\'zoomOut\', \''+ x +'\', \''+ y +'\');"> Zoom Out </div>' +
'<div class="menuItem"...