react google map doesn't update marker

React Google Map Doesn't Update Marker

Recently, I faced an issue where the marker in my React Google Map component was not updating. After researching and debugging for hours, I finally found the solution to this problem.

Possible Reasons for Marker Not Updating

  • Incorrect use of React's state and props
  • Incorrect implementation of the Google Maps API
  • Incorrect use of the Marker component

After ruling out the first two possibilities, I realized that my implementation of the Marker component was the issue.

Solution

To solve this issue, I had to set the position prop of the Marker component to a new LatLng object with updated coordinates.


import React, { Component } from 'react';
import { withGoogleMap, GoogleMap, Marker } from 'react-google-maps';

class Map extends Component {
  state = {
    position: {
      lat: 37.7749,
      lng: -122.4194,
    },
  };

  handleMarkerUpdate = () => {
    const newPosition = {
      lat: 40.7128,
      lng: -74.0060,
    };

    this.setState({ position: newPosition });
  };

  render() {
    const { position } = this.state;

    const MapWithMarker = withGoogleMap(() => (
      
        
      
    ));

    return (
      

In the above code snippet, I have created a Map component with a Marker. To update the position of the Marker, I have implemented a button click event that sets a new position in the component's state. This new position is then passed as a prop to the Marker component.

However, to ensure that the Marker component updates with the new position, I had to convert the new position into a LatLng object using the window.google.maps.LatLng constructor.

By following these steps, I was able to successfully update the Marker component in my React Google Map.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe