【问题标题】:How can I do to change the color of the marker?如何更改标记的颜色?
【发布时间】:2020-11-30 12:28:50
【问题描述】:

我正在使用带有传单的 React,但我不知道如何将标记的颜色从蓝色更改为红色。我查看了文档,但没有找到任何内容。

这是我的代码:

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

你知道我该怎么做吗?

非常感谢!

【问题讨论】:

  • 标记是一个图像,你可以用任何你想要的替换它。 dist/images/marker-icon.png,见this
  • 如何导入L?
  • @Peter 你已经在链接沙箱的Map 组件中完成了这项工作。

标签: javascript reactjs


【解决方案1】:

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

      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 changing Marker color

【讨论】:

  • 如何导入 L ?
  • 你能在这个链接中看到我的代码吗:codesandbox.io/s/m4k3x1ynl8
  • 是的,在 Map.js 文件的第 24 行。这就是您添加标记的位置。如果您删除当前的第 24 行并复制并粘贴我上面的代码,它将正常工作
【解决方案2】:

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

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);

【讨论】:

  • 如何导入 L ?
  • 其实我得到了这个`'L' is not defined no-undef`
  • 你可以看看 Map.js
  • 从“传单”导入 L
猜你喜欢
  • 1970-01-01
  • 2011-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-10
  • 1970-01-01
  • 1970-01-01
  • 2023-03-21
相关资源
最近更新 更多