Размещение маркера openlayers с использованием переменных в fromLonLat () (node js) - PullRequest
0 голосов
/ 15 марта 2020

Поэтому я создаю приложение, которое показывает текущее местоположение различных координат, которые должны быть показаны на карте с помощью маркеров, однако маркер не отображается в правильном местоположении, как показано на рисунке Маркеры пи c , где должно быть 5 маркеров в разных местах.

Вот код для отображения маркеров:

 for (let i = 1; i < 5; i++) {
          console.log(typeof (coord[i]));

          var element = document.createElement('div');
          element.innerHTML = '<img src="https://cdn.mapmarker.io/api/v1/fa/stack?size=50&color=DC4C3F&icon=fa-microchip&hoffset=1" />';
          var marker = new Overlay({
              position: fromLonLat([coord[i]], 'EPSG:3857') ,
              positioning: 'center-center',
              element: element,
              stopEvent: false
          });
          map.addOverlay(marker);
        }

Массив координат содержит массивы координат ex. [16.3725, 48.208889] Обратите внимание, что он работает правильно, когда координаты вводятся непосредственно в «fromLonLat» вместо переменной.

Есть ли способ исправить это?

1 Ответ

0 голосов
/ 15 марта 2020

Если coord - массив координат, проблема в том, что вместо передачи координаты coord[i] вы передаете массив координат [coord[i]]. Функция принимает координату в качестве параметра OL API - fromLonLat .

BTW, EPSG:3857 - значение по умолчанию, поэтому нет необходимости передавать ее в качестве параметра.

ОБНОВЛЕНИЕ: изменения в коде, указанном в комментариях

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import Overlay from 'ol/Overlay';
import Map from 'ol/Map';
import View from 'ol/View';
import Tile from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';
import Feature from 'ol/Feature';
import Point from 'ol/geom/Point';
import VectorSource from 'ol/source/Vector';
import VectorLayer from 'ol/layer/Vector';
import Style from 'ol/style/Style';
import Icon from 'ol/style/Icon';
import {fromLonLat} from 'ol/proj';
import {transform} from 'ol/proj';
import{DB_CONFIG} from './Config';
import firebase from 'firebase';
import 'firebase/database';

class Map2 extends Component {

    constructor (props) {
        super(props);        
        this.mapRef = null;
        this.setMapRef = element => {
            this.mapRef = element;
        }
        this.Longitude = props.Longitude;
        this.Latitude = props.Latitude;
        this.RFID = props.RFID;
        this.Name = props.Name;
        this.passengerID = props.passengerID;
        const {Name,RFID,Longitude,Latitude} = this.props;
        this.map = null; // <- keep a reference to the map
        this.vectorSource = null; // <- keep a reference to the source
    }

    componentDidMount() {
        const mapDOMNode = ReactDOM.findDOMNode(this.mapRef);
        this.vectorSource = new VectorSource();
        // Custom image for marker
        let iconStyle = new Style({
            image: new Icon({
                anchor: [0.5, 0.5],
                anchorXUnits: 'fraction',
                anchorYUnits: 'fraction',
                src: 'https://pngimg.com/uploads/gps/gps_PNG54.png',
                scale: 0.15
            })
        });  
        let vectorLayer = new VectorLayer({
            source: this.vectorSource,
            style: iconStyle,
            updateWhileAnimating: true,
            updateWhileInteracting: true,
        });
        // Create our initial map view
        let mapCenter = fromLonLat([ -74.0446426, 40.6892534 ]);
        let view = new View({
            center: mapCenter,
            zoom: 10
        });
        this.map = new Map({
            target: mapDOMNode,
            view: view,
            layers: [
                new Tile({
                    source: new OSM(),
                }),
                vectorLayer,
            ],
            loadTilesWhileAnimating: true,
        });
        // get data from firebase
        firebase.database().ref().child("Passengers").orderByChild("Name")
        .on("value",snapshot => {
            if (snapshot.exists() && Name && Longitude && Latitude)){
                const iconFeature = new Feature({
                    type: 'click',
                    geometry: new Point(
                        transform([Longitude, Latitude], 'EPSG:4326', 'EPSG:3857')
                    )
                });
                this.vectorSource.addFeature(iconFeature);
            }
        });
    };

    render() {
        const styles = { height: '100%', width: '100%'}
        return(
            <div style={styles} ref={this.setMapRef}></div>
        );
    }
}

export default Map2
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...