I have a WebView vehicle tracking application. I completed everything, but I could not manage to draw the path. What is the problem here?
var vectorSource = new ol.source.Vector(),
url_osrm_nearest = '//router.project-osrm.org/nearest/v1/driving/',
url_osrm_route = '//router.project-osrm.org/route/v1/driving/',
icon_url = '//cdn.rawgit.com/openlayers/ol3/master/examples/data/icon.png',
vectorLayer = new ol.layer.Vector({
source: vectorSource
}),
styles = {
route: new ol.style.Style({
stroke: new ol.style.Stroke({
width: 6, color: [40, 40, 40, 0.8]
})
}),
icon: new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 1],
src: icon_url
})
})
};
var utils = {
getNearest: function(coord){
var coord4326 =coord;
return new Promise(function(resolve, reject) {
//make sure the coord is on street
fetch(url_osrm_nearest + coord4326.join()).then(function(response) {
// Convert to JSON
return response.json();
}).then(function(json) {
if (json.code === 'Ok') resolve(json.waypoints[0].location);
else reject();
});
});
},
createFeature: function(coord) {
feature = new ol.Feature({
type: 'place',
geometry: new ol.geom.Point(coord)
});
//feature.setStyle(iconStyle3);
vectorSource.addFeature(feature);
},
createRoute: function(polyline) {
var route = new ol.format.Polyline({
factor: 1e5,
}).readGeometry(polyline);
feature = new ol.Feature({
type: 'route',
geometry: route
});
feature.setStyle(styles.route);
vectorSource.addFeature(feature);
},
to4326: function(coord) {
return ol.proj.transform([
parseFloat(coord[0]), parseFloat(coord[1])
]);
}
};
view = new ol.View({
center: [34.061624811814305,39.44893665949777],
zoom: 16,
projection: 'EPSG:4326',
});
const map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM(),
}),
vectorLayer
],
target: 'map',
view: view,
});
const markerEl = document.getElementById('geolocation_marker');
const marker = new ol.Overlay({
positioning: 'center-center',
element: markerEl,
stopEvent: false
});
map.addOverlay(marker);
const markerEl2 = document.getElementById('geolocation_marker_musteri');
const marker2 = new ol.Overlay({
positioning: 'center-center',
element: markerEl2,
stopEvent: false
});
map.addOverlay(marker2);
const positions = new ol.geom.LineString([], ('XYZM'));
feature.getGeometry().setCoordinates([longi_,lati_]);
utils.getNearest([longi_,lati_]);
utils.getNearest([longi__v,lati_]);
utils.createFeature([longi__v,lati_]);
var point1 = [longi_,lati_];
var point2 = [longi__v,lati_];
fetch(url_osrm_route + point1 + ';' + point2).then(function(r) {
return r.json();
}).then(function(json) {
if(json.code !== 'Ok') {
return;
}
utils.createRoute(json.routes[0].geometry);
It draws a path as follows.
I'm looking at the route in openstreetmap with the same coordinates. It gives the correct route there. By the way, the coordinates are someone dynamic, that is, the position of the device. The other coordinate is stationary.
Edit:
I've realized now. It draws a straight line between two points. It doesn't draw according to the road.
I tried hard and couldn't find the solution. I also used openrouteservice instead of osm for geometry.
function get_JSON(coor1,coor2)
{
let request = new XMLHttpRequest();
request.open('POST', "https://api.openrouteservice.org/v2/directions/driving-car/json");
request.setRequestHeader('Accept', 'application/json, application/geo+json, application/gpx+xml, img/png; charset=utf-8');
request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Authorization', 'api_key');
request.onreadystatechange = function () {
if (this.readyState === 4) {
var data_json= JSON.parse(this.responseText);
utils.createRoute(data_json.routes[0].geometry);
}
};
const body = '{"coordinates":[['+coor1+'],['+coor2+']],"radiuses":120000}';
request.send(body);
}
Related
Trying to use a featureLoader in OpenLayers 6 so that I can gain access to the featuresloadend event but when I try to load the features nothing shows up. Further examination of the pointLayer shows that no features had been added to the Layer.
const pointSource = new ol.source.Vector({
format: new ol.format.GeoJSON(),
loader: function(extent, resolution, projection, success, failure) {
var proj = projection.getCode();
var url = '/awdndb/monitor/geoawdndata?product=scqc1440&begin=2022-09-20&end=2022-09-20&sensor=AirTempMax2m&units=si';
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
var onError = function() {
vectorSource.removeLoadedExtent(extent);
failure();
}
xhr.onerror = onError;
xhr.onload = function() {
if (xhr.status == 200) {
var features = pointSource.getFormat().readFeatures(JSON.parse(xhr.responseText));
pointSource.addFeatures(features);
success(features);
}
else {
onError();
}
}
xhr.send();
}
})
const pointLayer = new ol.layer.Vector({
source: pointSource,
title: 'pointLayer',
style: pointFunction
});
//Setup Overlay
const overlay = new ol.Overlay({
element: container,
autoPan: true,
autoPanAnimation: {
duration: 250
}
});
//Setup Map Object
const map = new ol.Map({
target: 'map',
overlays: [overlay],
view: new ol.View({
center: [-10997148, 4569099],
zoom: 5
})
});
map.addLayer(baseLayer);
map.addLayer(pointLayer);
the json far to big to include entire code):
{"type":"FeatureCollection","crs":{"type":"name","properties":{"name":"EPSG:4326"}},"features":[{"type":"Feature","geometry":{"type":"Point","coordinates":[-94.98,48.86]},"properties":{"name":"Williams 6N","state":"MN","county":"Lake of the Woods","sensors":["TIMESTAMP","AirTempMax2m","AirTempMax2m_SCQC_Flag"],"units":["TS","C","Flag"],"data":[["2022-09-20",20.58," "]]}},{"type":"Feature","geometry":{"type":"Point","coordinates":[-100.61,38.51]},"properties":{"name":"Lane","state":"KS","county":"Lane","sensors":["TIMESTAMP","AirTempMax2m","AirTempMax2m_SCQC_Flag"],"units":["TS","C","Flag"],"data":[["2022-09-20",37.86," "]]}},{"type":"Feature","geometry":{"type":"Point","coordinates":[-96.59,39.21]},"properties":{"name":"Manhattan","state":"KS","county":"Riley","sensors":["TIMESTAMP","AirTempMax2m","AirTempMax2m_SCQC_Flag"],"units":["TS","C","Flag"],"data":[["2022-09-20",37.46," "]]}},{"type":"Feature","geometry":{"type":"Point","coordinates":[-108.72,37.53]},"properties":{"name":"Yellow Jacket","state":"CO","county":"Montezuma","sensors":["TIMESTAMP","AirTempMax2m","AirTempMax2m_SCQC_Flag"],"units":["TS","C","Flag"],"data":[["2022-09-20",24.62," "]]}},{"type":"Feature","geometry":{"type":"Point","coordinates":[-102.57,48.49]},"properties":{"name":"Powers Lake 6SE","state":"ND","county":"Mountrail","sensors":
...
I am a relative beginner to using OpenLayers so I was playing around with some of the examples given on the OpenLayers website. When trying the image-vector-layer example, I had a problem where it would work fine with a json online, but when using a local geojson file the response under the networks section for the geojson file would be an html instead, giving the error "Unexpected token < in JSON at position 0". Attached is my javascript below, the error is occurring at the "url: data/countries.geojson". Is there any way I can use a local file instead of an online link? Thank you!
import 'ol/ol.css';
import GeoJSON from 'ol/format/GeoJSON';
import Map from 'ol/Map';
import VectorImageLayer from 'ol/layer/VectorImage';
import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';
import View from 'ol/View';
import {Fill, Stroke, Style} from 'ol/style';
const style = new Style({
fill: new Fill({
color: '#eeeeee',
}),
});
const vectorLayer = new VectorImageLayer({
background: 'lightblue',
imageRatio: 2,
source: new VectorSource({
url: 'data/countries.geojson',
format: new GeoJSON(),
}),
style: function (feature) {
const color = feature.get('COLOR') || '#eeeeee';
style.getFill().setColor(color);
return style;
},
});
const map = new Map({
layers: [vectorLayer],
target: 'map',
view: new View({
center: [0, 0],
zoom: 1,
}),
});
const featureOverlay = new VectorLayer({
source: new VectorSource(),
map: map,
style: new Style({
stroke: new Stroke({
color: 'rgba(255, 255, 255, 0.7)',
width: 2,
}),
}),
});
let highlight;
const displayFeatureInfo = function (pixel) {
const feature = map.forEachFeatureAtPixel(pixel, function (feature) {
return feature;
});
const info = document.getElementById('info');
if (feature) {
info.innerHTML = feature.get('ECO_NAME') || ' ';
} else {
info.innerHTML = ' ';
}
if (feature !== highlight) {
if (highlight) {
featureOverlay.getSource().removeFeature(highlight);
}
if (feature) {
featureOverlay.getSource().addFeature(feature);
}
highlight = feature;
}
};
map.on('pointermove', function (evt) {
if (evt.dragging) {
return;
}
const pixel = map.getEventPixel(evt.originalEvent);
displayFeatureInfo(pixel);
});
map.on('click', function (evt) {
displayFeatureInfo(evt.pixel);
});
How do you make it so wherever you click on the map, the Icon added on the map just instantly teleports to those coordinates? Currently in the official Open Layers 6 'Examples' page, it shows the drag and drop example with the following example:
import 'ol/ol.css';
import Feature from 'ol/Feature';
import Map from 'ol/Map';
import Point from 'ol/geom/Point';
import TileJSON from 'ol/source/TileJSON';
import VectorSource from 'ol/source/Vector';
import View from 'ol/View';
import {Icon, Style} from 'ol/style';
import {Modify} from 'ol/interaction';
import {Tile as TileLayer, Vector as VectorLayer} from 'ol/layer';
const iconFeature = new Feature({
geometry: new Point([0, 0]),
name: 'Null Island',
population: 4000,
rainfall: 500,
});
const iconStyle = new Style({
image: new Icon({
anchor: [0.5, 46],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
src: 'data/icon.png',
}),
});
iconFeature.setStyle(iconStyle);
const vectorSource = new VectorSource({
features: [iconFeature],
});
const vectorLayer = new VectorLayer({
source: vectorSource,
});
const rasterLayer = new TileLayer({
source: new TileJSON({
url: 'https://a.tiles.mapbox.com/v3/aj.1x1-degrees.json?secure=1',
crossOrigin: '',
}),
});
const target = document.getElementById('map');
const map = new Map({
layers: [rasterLayer, vectorLayer],
target: target,
view: new View({
center: [0, 0],
zoom: 3,
}),
});
const modify = new Modify({
hitDetection: vectorLayer,
source: vectorSource,
});
modify.on(['modifystart', 'modifyend'], function (evt) {
target.style.cursor = evt.type === 'modifystart' ? 'grabbing' : 'pointer';
});
const overlaySource = modify.getOverlay().getSource();
overlaySource.on(['addfeature', 'removefeature'], function (evt) {
target.style.cursor = evt.type === 'addfeature' ? 'pointer' : '';
});
map.addInteraction(modify);
Their wiki does not mention about any convenient property like Icon.setPosition. Thank you.
You add a click listener to the map and change the geometry of the feature:
map.on('click', function (event) {
iconFeature.getGeometry().setCoordinates(event.coordinate);
});
I am trying to display some markers on the OSM. This works so far, but i just wanted to change the default marker against another one from a local path, but i didnt know how to add this to my code, i have tried the setStyle but i didnt know how to apply it correctly. It would be also nice if am able to style the icon too.
I also want markers to be dynamically displayed, because i am doing this manually each time through
var layer = new ol.layer.Vector({source: new ol.source.Vector({
features: [
new ol.Feature({
geometry: new ol.geom.Point(ol.proj.fromLonLat([4.35247, 50.84673]))
}),
new ol.Feature({
geometry: new ol.geom.Point(ol.proj.fromLonLat([4.35247, 52.84673]))
}),
]
});
Here is a snippet of the full code that i use
/* open street map newest version */
var map = new ol.Map({
target: 'map', // the div id
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
view: new ol.View({
center: ol.proj.fromLonLat([4.35247, 52.520008]),
zoom: 4
})
});
// add a marker to the map
var layer = new ol.layer.Vector({
source: new ol.source.Vector({
features: [
new ol.Feature({
geometry: new ol.geom.Point(ol.proj.fromLonLat([4.35247, 50.84673]))
}),
new ol.Feature({
geometry: new ol.geom.Point(ol.proj.fromLonLat([4.35247, 52.84673]))
})
]
})
});
map.addLayer(layer);
//initialize the popup
var container = document.getElementById('popup');
var content = document.getElementById('popup-content');
var overlay = new ol.Overlay({
element: container,
autoPan: true,
autoPanAnimation: {
duration: 250
}
});
map.addOverlay(overlay);
//display the pop with on mouse over
map.on('pointermove', function (event) {
if (map.hasFeatureAtPixel(event.pixel) === true) {
var coordinate = event.coordinate;
content.innerHTML = '<b>Hello world!</b><br />I am a popup.';
overlay.setPosition(coordinate);
}
else {
overlay.setPosition(undefined);
closer.blur();
}
});
Fixed this, the issue was from the local path. If this may help anyone i added this to my code
layer.setStyle(new ol.style.Style({
image: new ol.style.Icon({
src: 'https://wiki.openstreetmap.org/w/images/0/0c/Hgv.png'
})
}));
i am trying to get some Dots on my Map with Openlayer. The Maps works fine. I got a JSON file with longitude and latitude and i want them to appear on my map. But it is not working. the parsing wont work somehow.
Error 1:
Error 2:
JSON file: https://github.com/CodeforChemnitz/Haltestellen/blob/gh-pages/haltestellen.json
My Code:
<div class="main-container-cvag">
<div id="map" class="map"></div>
<script src="https://openlayersbook.github.io/openlayers_book_samples/assets/ol3/js/ol.js"></script>
<script>
// Declare a Tile layer with an openstreetmap
var osmLayer = new ol.layer.Tile({
source: new ol.source.OSM()
});
// latitude and longitude to Chemnitz projection
var chemnitz = ol.proj.transform([12.9213697, 50.827845], 'EPSG:4326', 'EPSG:3857');
// Create a View, set it center and zoom level
var view = new ol.View({
center: chemnitz,
zoom: 13
});
//source
var chemnitzStationSource = new ol.source.Vector();
//dot style
function dotstyle(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];
}
//new layer
var chemnitzStations = new ol.layer.Vector({
source: chemnitzStationSource,
style: dotstyle
})
//new Map
var map = new ol.Map({
target: 'map',
layers: [osmLayer, chemnitzStations],
view: view
});
$.ajax({
url: "haltestellen.json",
dataType: "jsonp",
crossDomain: true,
success: function(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.stations);
var coordinate = transform([parseFloat(item.longitude), parseFloat(item.latitude)]);
var geometry = new ol.geom.Point(coordinate);
feature.setGeometry(geometry);
chemnitzStationSource.addFeature(feature);
console.log(parseFloat(item.longitude));
});
}
});
map.addLayer(osmLayer);
// Set the view for the map
map.setView(view);
</script>
</div>
Can someone help me what to do? :)
You are loading JSON, but have dataType: "jsonp".
Change it to dataType: "json",.