开发者问题收集

ReactJs Leaflet 标记位置问题

2020-04-12
3054

我正在尝试使用 leaflet 在我的 reactjs 项目中添加地图,并希望在地图上显示车辆的位置。我为此做了一个示例用法。但是当我在地图上使用标记时,我看到(如您在这张图片中看到的那样):

标记的左上侧贴在我的位置。我想看到标记的底部像圆圈一样位于我的位置中心。但我做不到。我读过 react-leaflet 文档,但没有看到这个参数。如果你能帮助我,我将不胜感激。谢谢

import React, { Component } from 'react'
import Leaflet from 'leaflet';
import { Map, CircleMarker, TileLayer, Marker, Popup } from 'react-leaflet'
import 'leaflet/dist/leaflet.css';

import icon from 'leaflet/dist/images/marker-icon.png';
import iconShadow from 'leaflet/dist/images/marker-shadow.png';

let DefaultIcon = Leaflet.icon({
    iconUrl: icon,
    shadowUrl: iconShadow
});

Leaflet.Marker.prototype.options.icon = DefaultIcon;

class SimpleExample extends React.Component {
  constructor(props) {
    super();
    this.state = {
      lat: 39.9653301,
      lng: 32.7760817,
      zoom: 5,
      markerPoint: {
        x: 320,
        y: 192
      }
    };
    this.refMap = React.createRef();
  }

  render() {
    const { lat, lng, zoom } = this.state;
    const position = [lat, lng];
    return (
      <Map ref={this.refMap} center={position} zoom={zoom}   style={{ height: '400px', width: '100%' }}>
        <TileLayer
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
          attribution="&copy; <a href=&quot;http://osm.org/copyright&quot;>OpenStreetMap</a> contributors"
        />
        <Marker position={position} draggable="True" pane="popupPane" >
        </Marker>
        <CircleMarker
        center={position}
        color='green'
        fillColor='red'
        radius={20}
        fillOpacity={0.5}
        stroke={false}
>
            <Popup>
              <span>A pretty CSS3 popup. <br/> Easily customizable.</span>
            </Popup>
      </CircleMarker>
      </Map>
    );
  }
}

export default SimpleExample;
1个回答

定义正确的 iconAnchor 大小,标记将被放置在正确的位置。

let DefaultIcon = Leaflet.icon({
  iconSize: [25, 41],
  iconAnchor: [10, 41],
  popupAnchor: [2, -40],
  iconUrl: icon,
  shadowUrl: iconShadow
});

演示

kboul
2020-04-14