Здесь я использую стиль отдыха из слоя Ordnance Survey (OS) карты OpenLayers. ОС - это британское базовое картографическое агентство. В приведенном ниже коде мы используем EPSG: 27700 для стиля отдыха. В коде мы можем создавать маршруты и отображать точки с помощью Linestring и маркера точек. Но не в состоянии сделать линейную линию и очки перетаскиваемыми. Как пользователь хочет редактировать существующие маршруты. Но при создании маршрутов с использованием Linestring линия и точки перетаскиваются. Я искал различные сайты для решения, но не смог найти правильное решение.
Вот мой код: -
<html>
<head>
<title>OS Maps API | Basic Map (EPSG:27700) | OpenLayers</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.1.1/css/ol.css" />
<style>
body { margin:0; padding:0; }
form {
display: block;
}
#map {
position:absolute;
top:0;
bottom:0;
width: 800px;
height: 500px;
}
.span12 {
width:800px;
height: 500px;
}
</style>
</head>
<body>
<div class="container-fluid">
<div class="">
<div class="span12">
<div id="map" class="map"></div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.1.1/build/ol.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.5.0/proj4.js"></script>
<script>
var apiKey = 'RzWWIxK9fGG2EsmvrR2ayy36zPetIKMO';
var base_url = window.location.origin;
var icon_url = "/img/marker.png";
var serviceUrl = 'https://osdatahubapi.os.uk/OSMapsAPI/wmts/v1';
var parser = new ol.format.WMTSCapabilities();
var map;
// Setup the EPSG:27700 (British National Grid) projection.
proj4.defs("EPSG:27700", "+proj=tmerc +lat_0=49 +lon_0=-2 +k=0.999601 +x_0=400000 +y_0=-100000 +ellps=airy +towgs84=446.448,-125.157,542.060,0.1502,0.2470,0.8421,-20.4894 +datum=OSGB36 +units=m +no_defs");
ol.proj.proj4.register(proj4);
var bng = ol.proj.get('EPSG:27700');
bng.setExtent([ -238375.0, 0.0, 900000.0, 1376256.0 ]);
// console.log(ol.proj.fromLongLat(points, 'EPSG:27700'));
fetch(serviceUrl + '?key=' + apiKey + '&service=WMTS&request=GetCapabilities&version=2.0.0')
.then(response => response.text())
.then(text => {
var result = parser.read(text);
var options = ol.source.WMTS.optionsFromCapabilities(result, {
layer: 'Leisure_27700'
});
var source = new ol.source.WMTS(options);
var layer = new ol.layer.Tile({ source: source });
var viewOptions = {
projection: options.projection,
resolutions: options.tileGrid.getResolutions(),
center: [ 337297, 503695 ],
zoom: 7
}
// Set the default center of the map view.
map = new ol.Map({
layers: [ layer ],
target: 'map',
view: new ol.View(viewOptions)
});
var cord = new Array(['336555.3571805824', '503945.0759345037'], ['336630.3808312133', '504033.339052893'], ['336895.1701863812', '504055.4048324903'], ['337314.41999873036', '503945.0759345037'], ['337250.42923789815', '503808.2681010003']);
var points = new Array();
var features = new Array();
cord.forEach(function(element) {
points.push([parseFloat(element[0]), parseFloat(element[1])]);
var iconFeature = new ol.Feature({
geometry: new ol.geom.Point([parseFloat(element[0]), parseFloat(element[1])])
});
//create style for your feature...
var iconStyle = [
new ol.style.Style({
image: new ol.style.Icon(({
scale: 0.7,
rotateWithView: false,
anchor: [0.5, 1],
anchorXUnits: 'fraction',
anchorYUnits: 'fraction',
opacity: 1,
src: 'marker.png'
})),
zIndex: 8
}),
new ol.style.Style({
image: new ol.style.Circle({
radius: 8,
fill: new ol.style.Fill({
color: '#ffffff'
}),
stroke: new ol.style.Stroke({
color: '#2ECC40',
width: 4
})
})
})
];
iconFeature.setStyle(iconStyle);
features.push(iconFeature);
});
/*
* create vector source
* you could set the style for all features in your vectoreSource as well
*/
var vectorSource = new ol.source.Vector({
features: features //add an array of features
//style: iconStyle //to set the style for all your features...
});
var vectorLayer = new ol.layer.Vector({
source: vectorSource
});
map.addLayer(vectorLayer);
var marker = new ol.Feature({
geometry: new ol.geom.LineString(points), // Cordinates of New York's Town Hall
});
var vectorSource = new ol.source.Vector({
features: [marker]
});
var markerVectorLayer = new ol.layer.Vector({
source: vectorSource,
style: new ol.style.Style({
fill: new ol.style.Fill({
color: '#2ECC40',
width: 7
}),
stroke: new ol.style.Stroke({
color: '#2ECC40',
width: 5
}),
icon: new ol.style.Icon({
src: icon_url
})
})
});
map.addLayer(markerVectorLayer);
var features = new ol.Collection();
var featureOverlay = new ol.layer.Vector({
source: new ol.source.Vector({
features: features
}),
style: new ol.style.Style({
fill: new ol.style.Fill({
color: '#2ECC40'
}),
stroke: new ol.style.Stroke({
color: '#2ECC40',
width: 5
}),
image: new ol.style.Icon({
src: icon_url
})
})
});
featureOverlay.setMap(map);
var modify = new ol.interaction.Modify({
features: features,
// the SHIFT key must be pressed to delete vertices, so
// that new vertices can be drawn at the same position
// of existing vertices
deleteCondition: function(event) {
return ol.events.condition.shiftKeyOnly(event) && ol.events.condition.singleClick(event);
}
});
map.addInteraction(modify);
var draw; // global so we can remove it later
function addInteraction() {
draw = new ol.interaction.Draw({
features: features,
type: ('LineString'), /** #type {ol.geom.GeometryType} */
style: new ol.style.Style({
stroke: new ol.style.Stroke({
color: '#2ECC40',
width: 4
}),
image: new ol.style.Circle({
radius: 7,
fill: new ol.style.Fill({
color: '#2ECC40'
})
})
})
});
map.addInteraction(draw);
}
addInteraction();
map.on('click', function(event) {
var feature = map.getFeaturesAtPixel(event.pixel)[0];
if (feature) {
var coordinate = feature.getGeometry().getCoordinates();
}
});
});
</script>
</body>
</html>