Skip to content
the poor coder

react google map doesn't update marker

Poor Man
Published
Reading time
1 min read
On this page

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.

Text

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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC