繁体   English   中英

如何更改标记的颜色?

[英]How can I do to change the color of the marker?

我将 React 与 leaflet 一起使用,但我不知道如何将标记的颜色从蓝色更改为红色。 我查看了文档,但没有找到任何关于此的内容。

这是我的代码:

import React from 'react';
import { render } from 'react-dom';
import Map from './Map';

class App extends React.Component {
  state = { markerPosition: { lat: 49.8419, lng: 24.0315 } };
  moveMarker = () => {
    const { lat, lng } = this.state.markerPosition;
    this.setState({
      markerPosition: {
        lat: lat + 0.0001,
        lng: lng + 0.0001, 
      }
    });
  };
  render() {
    const { markerPosition } = this.state;
    return (
      <div>
        <Map markerPosition={markerPosition} />
        <div>Current markerPosition: lat: {markerPosition.lat}, lng: {markerPosition.lng}</div>
        <button
          onClick={this.moveMarker}
        >
          Move marker
        </button>
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));

https://codesandbox.io/s/m4k3x1ynl8

你知道我该怎么做吗?

非常感谢!

由于标记是一个图标,您可以更改它使用的图标。

      const redIcon = new L.Icon({
      iconUrl:
        "https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-red.png",
      shadowUrl:
        "https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/marker-shadow.png",
      iconSize: [25, 41],
      iconAnchor: [12, 41],
      popupAnchor: [1, -34],
      shadowSize: [41, 41]
    });
    // add marker
    this.marker = L.marker(this.props.markerPosition, {
      icon: redIcon
    }).addTo(this.map);

有关更多信息,请参阅此: Leaflet 更改标记颜色

首先,您需要创建新的图标实例,如下所示

const icon = new L.Icon({
  iconUrl:
    "https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-green.png",
  shadowUrl:
    "https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/marker-shadow.png",
  iconSize: [25, 41],
  iconAnchor: [12, 41],
  popupAnchor: [1, -34],
  shadowSize: [41, 41]
});

然后你应该将它添加到选项

// add marker
this.marker = L.marker(this.props.markerPosition, { icon }).addTo(this.map);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM