Почему маркер не устанавливается?
Задача в том, чтобы маркер ставился в заданную из переменной точку. Если заменить в параметре geometry переменную geoposition на конкретные координаты - маркер установится, если же ставить переменную - маркера не будет, без каких-либо ошибок в консоли. В чём заключается проблема?
geoposition = '38.997190, 45.130683';// координаты нужной позиции, на которую будет установлен маркер
//Создание иконки местонахождения пользователя
var iconFeature = new ol.Feature({
geometry: new ol.geom.Point(ol.proj.transform([geoposition], 'EPSG:4326', 'EPSG:3857')),
name: 'Null Island',
population: 4000,
rainfall: 500
});
var iconStyle = new ol.style.Style({
image: new ol.style.Icon(/** @type {olx.style.IconOptions} */({
anchor: [0.511, 310],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
opacity: 1,
scale: .2,
src: 'images/phGeoPos.png'
}))
});
iconFeature.setStyle(iconStyle);
var vectorSource = new ol.source.Vector({
features: [iconFeature]
});
var vectorLayer = new ol.layer.Vector({
source: vectorSource
});
//Создание карты на сайте
function loadMap() {
var centerpos = [38.997190, 45.130683];
var newpos = ol.proj.transform(centerpos, 'EPSG:4326', 'EPSG:900913');
const map = new ol.Map({
// устанавливает вид на заданное место и масштаб
view: new ol.View({
center: newpos,
projection: 'EPSG:900913',
zoom: 12,
maxZoom: 20,
minZoom: 5,
extent: [4262967.307515293, 5592508.683331995, 4429711.492867963, 5697114.645076073]
}),
minExtent: 10,
// добавляет тайловый слой OpenStreetMap
layers: [
new ol.layer.Tile({
source: new ol.source.OSM({
tileSize: 512,
maxResolution: 180 / 512,
wrapX: true,
})
}),
vectorLayer,
],
keyboardEventTarget: document,
target: 'map',
});
map.on('click', function (e) {
let coord = e.coordinate
console.log(coord);
})
}
//Получение координат пользователя сайта (работает только если на устройстве есть датчик)
function coordinateUser() {
var writeCoord = document.getElementById('coord');
var msg = 'Координаты отсутствуют.';
console.log(navigator.geolocation);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
writeCoord.textContent = 'Определение местоположения..';
} else {
writeCoord.textContent = msg;
}
function success(position) {
var lat = (position.coords.latitude).toFixed(8);
var lon = (position.coords.longitude).toFixed(8);
var accuracy = position.coords.accuracy;
msg = `${lat}, ${lon} <br>погрешность(в метрах): ${accuracy}`;
writeCoord.innerHTML = msg;
//geoposition = `${lon},${lat}`
}
function error(msg) {
writeCoord.textContent = msg;
console.log(msg.code);
}
}
const promise = new Promise((resolve, reject) => {
const randomNumber = Math.random();
setTimeout(() => {
if (randomNumber < .6) {
resolve('Все прошло отлично!');
} else {
reject('Что-то пошло не так');
}
}, 2000);
});
Ответы (1 шт):
Автор решения: Nickolai Bondarenko
→ Ссылка
В общем, решил данную проблему путём поиска координат с помощью встроенных средств openlayers, вместо навигатора.
// Создание слоя OSM на странице сайта
var centerpos = [38.997190, 45.130683];
var newpos = ol.proj.transform(centerpos, 'EPSG:4326', 'EPSG:900913');
// Установка визуализации OSM
var view = new ol.View({
projection: 'EPSG:900913',
center: newpos,
zoom: 2,
maxZoom: 20,
minZoom: 5,
extent: [4262967.307515293, 5592508.683331995, 4429711.492867963, 5697114.645076073]
});
// Установка слоя ОСМ
var map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM({
tileSize: 512,
maxResolution: 180 / 512,
wrapX: true,
view: view,
}),
})],
keyboardEventTarget: document,
target: 'map',
view: view,
minExtent: 10,
});
// Получить координаты щелчком мыши
map.on('click', function (e) {
let coord = e.coordinate
console.log(coord);
})
//Создание иконки местонахождения пользователя
var geolocation = new ol.Geolocation({
trackingOptions: {
enableHighAccuracy: true,
},
projection: view.getProjection(),
});
function el(id) {
return document.getElementById(id);
}
el('whereAmI').addEventListener('change', function () {
geolocation.setTracking(this.checked);
console.log(geolocation.projection);
});
var accuracyFeature = new ol.Feature();
geolocation.on('change:accuracyGeometry', function () {
accuracyFeature.setGeometry(geolocation.getAccuracyGeometry());
console.log(accuracyFeature);
});
var positionFeature = new ol.Feature();
positionFeature.setStyle(
new ol.style.Style({
image: new ol.style.Circle({
radius: 6,
fill: new ol.style.Fill({
color: '#3399CC',
}),
stroke: new ol.style.Stroke({
color: '#fff',
width: 2,
}),
}),
})
);
geolocation.on('change:position', function () {
var coordinates = geolocation.getPosition();
positionFeature.setGeometry(coordinates ? new ol.geom.Point(coordinates) : null);
});
new ol.layer.Vector({
map: map,
source: new ol.source.Vector({
features: [accuracyFeature, positionFeature],
}),
});