JSFiddle - React, Tailwind, and code Playground
HTML
<link rel="stylesheet" href="http://openlayers.org/en/v3.14.2/css/ol.css">
<script src="http://openlayers.org/en/v3.11.2/build/ol.js"></script>
<div id="map" class="map"></div>
JavaScript
var vehicle = {
'x': 1700010,
'y': 6100000
};
//CREATING VEHICLE
var stroke = new ol.style.Stroke({color: 'black', width: 2});
var fill = new ol.style.Fill({color: 'red'});
var styles = {
'triangle': [new ol.style.Style({
image: new ol.style.RegularShape({
fill: fill,
stroke: stroke,
points: 3,
radius: 10,
rotation: Math.PI / 4,
angle: 0
})
})]
};
var feature;
var coordinates = [vehicle.x,vehicle.y];
feature = new ol.Feature(new ol.geom.Point(coordinates));
feature.setStyle(styles['triangle']);
var source = new ol.source.Vector({
features: [feature]
});
var vectorLayer = new ol.layer.Vector({
source: source
});
//CREATING MAP
var map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
vectorLayer
],
target: 'map',
view: new ol.View({
center: [vehicle.x,vehicle.y],
zoom: 13
})
});
//NOW SETTING INTERVAL UP IN ORDER TO CENTER MAP AT A PARTICULAR POINT (vehicle's position + a certain vector)
setInterval(() => {
var size = map.getSize();
//Getting pixel coordinates
var centerPixelX = size[0]/2;
var tierPixelY = size[1]/3;
var point = [centerPixelX, 2*tierPixelY];
//No problem here
var position = map.getPixelFromCoordinate(coordinates);
//Creating vector from vehicle to pixel
var X = point[0];
var Y = point[1];
var x = position[0];
var y = position[1];
var vector = {
'vx': (x-X),
'vy': (y-Y)
};
//Centering map to the vector coordinates
var newCenter = [size[0]/2 + vector.vx, size[1]/2 + vector.vy];
map.getView().setCenter(map.getCoordinateFromPixel(newCenter));
}, 200);