简体   繁体   中英

Single custom marker google maps API in react

I have been working with Google Maps & Places API and have successfully got it working using react hooks to allow the user to drop markers, onClick info window, auto-complete place search and Geolocation.

However, what I need is that onClick it will only add a single marker which will change location every time the user clicks a new coord. Not add multiple markers on every click as it currently does.

Code below:

const [markers, setMarkers] = useState([]);
const [selected, setSelected] = useState(null);


  const onMapClick = useCallback((event) => {
    setMarkers((current) => [
      ...current,
      {
        lat: event.latLng.lat(),
        lng: event.latLng.lng(),
        time: new Date(),
      },
    ]);
  }, []);

...

return (

 <GoogleMap
        mapContainerStyle={mapContainerStyle}
        zoom={13}
        center={center}
        onClick={onMapClick}
        onLoad={onMapLoad}
      >
        {markers.map((marker) => (
          <Marker
            key={marker.time.toISOString()}
            position={{ lat: marker.lat, lng: marker.lng }}
            icon={{
              url: "/crane-pin.svg",
              scaledSize: new window.google.maps.Size(40, 40),
              origin: new window.google.maps.Point(0, 0),
              anchor: new window.google.maps.Point(15, 15),
            }}
            onClick={() => {
              setSelected(marker);
            }}
          />
        ))}

...

  </GoogleMap>

any help would be appreciated!

To achieve your use case, you need to have access to the marker object and use the setPosition method to change the position of the marker to the clicked coordinates in the map.

Are you using any google maps react library? Here is a sample reactjs code that implements this without using any react libraries. Code snippet below:

import React, { Component } from "react";
import { render } from "react-dom";
import Map from "./Map";
import "./style.css";

class App extends Component {
  render() {
    return (
      <div id="container">
        <Map
          id="myMap"
          options={{
            center: { lat: 37.769, lng: -122.446 },
            zoom: 12,
          }}
          onMapLoad={(map) => {
            let marker = new google.maps.Marker({
              position: { lat: 37.769, lng: -122.446 },
              map: map,
            });

            //Changing Marker position for clicked coordinate
            map.addListener("click", (event) => {
              marker.setPosition(event.latLng);
            });
          }}
        />
      </div>
    );
  }
}

export default App;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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