1

I am using React with leaflet but I do not know how to change the marker's color from blue to red. I looked at the documentation but I didn't find anything on this.

Here is my code :

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

Do you know how can I do this?

Thank you very much!

Armando Guarino
  • 1,120
  • 1
  • 5
  • 16
Peter
  • 105
  • 3
  • 10

2 Answers2

0

Since marker is an icon you can change the icon that it use.

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

Refer to this for more information: Leaflet changing Marker color

TheLastStark
  • 770
  • 5
  • 18
0

First you need to create new icon instance like below

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

and then you should add it to options

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