Search code examples
javascriptreactjsgoogle-mapsnext.jsreact-google-maps

React google map is not updating


Im using react-google-map, and I add poly line every marker in the map. But every time I delete a data the marker on the map wont disappear. Here is my code below.

Googlemap.js

 /*global google*/
import React, { Component } from "react";
import { Polyline } from "react-google-maps";
import {
  withGoogleMap,
  withScriptjs,
  Marker,
  GoogleMap,
  DirectionsRenderer,
} from "react-google-maps";

const Map = ({ places, zoom, center }) => {
  return (
    <GoogleMap defaultZoom={zoom} defaultCenter={center}>
      <Markers places={places} />

      <Polyline
        path={places}
        options={{
          strokeColor: "#FFE900",
          strokeOpacity: 2,
          strokeWeight: 3,
        }}
      />
    </GoogleMap>
  );
};

const Markers = ({ places }) => {
  return places.map((place) => {
    return (
      <Marker key={place.id} position={{ lat: place.lat, lng: place.lng }} />
    );
  });
};


class MapWithMarker extends Component {

  constructor(props) {
    super(props);
    this.state = { places: this.props.places }; //initialize initial state from props
  }

  render() {
    return (
      <div>
        <Map
          center={this.props.center}
          zoom={this.props.zoom}
          places={this.state.places}
          containerElement={<div style={{ height: `100vh`, width: "100% " }} />}
          mapElement={<div style={{ height: `100%` }} />}
        />
      </div>
    );
  }
}

export default withScriptjs(withGoogleMap(MapWithMarker));

maploader.js

import React, { Component, useState } from "react";
import "./config";
import Map from "./googlemap";

const App = () => {
  const place = places;

  return (
    <div>
      <Map
        googleMapURL="https://maps.googleapis.com/maps/api/js?key=API_KEY"
        loadingElement={<div style={{ height: `100%` }} />}
        containerElement={<div style={{ height: `100vh` }} />}
        mapElement={<div style={{ height: `100%` }} />}
        center={{ lat: 14.6091, lng: 121.0223 }}
        zoom={12}
        places={places}
      />
    </div>
  );
};

export default App;

Config.js

places = [
  {
    name: "Manila",
    title: "Newcastle",
    lat: 14.6091,
    lng: 121.0223,
    id: 1,
  },
  {
    name: "Taguig",
    title: "Sydney",
    lat: 14.5135352,
    lng: 121.0303829,
    id: 2,
  },
  {
    name: "Makati",
    title: "Melbourne",
    lat: 14.554592,
    lng: 121.0156802,
    id: 3,
  },
];

And here is the sample code of my button in my map.js. This the button that will delete the last object in array. Everytime i delete a data it should be reflected in the map which is not working but working in console.

function clickSubmit(e) {
    places.pop();
  }

Any help would be appreciated. :)


Solution

  • In removing a marker in Google Maps JavaScript API, you should call the setMap() method and pass a null argument. However, as you are using react-google-maps library which setMap() method seems to be not included per their documentation.

    You can implement your use case without using a library such as this sample code. Please use your API Key in Maps.js file for the code to work.

    Please see code snippet with inline comments of the component that shows this:

    import React, { Component } from "react";
    import { render } from "react-dom";
    import Map from "./Map";
    import "./style.css";
    import "./config";
    
    class App extends Component {
      render() {
        return (
          <div id="container">
            <input type="button" value="Delete " id="myBtn" />
            <Map
              id="myMap"
              options={{
                center: { lat: 14.6091, lng: 121.0223 },
                zoom: 12,
              }}
              onMapLoad={(map) => {
                let placeArray = [];
                let markersArray = [];
                let polylinePath = [];
                let polyline;
                //putting the places from config.js in an array
                {
                  places.map((markerJson) => placeArray.push(markerJson));
                }
                
                //Adding Marker for each coordinate in the array
                for (let i = 0; i < placeArray.length; i++) {
                  addMarker({ lat: placeArray[i].lat, lng: placeArray[i].lng });
                }
                //function for creating polyline
                createPolyline();
    
                document.getElementById("myBtn").addEventListener("click", function () {
                    //Removing marker of the last coordinate in the map
                    markersArray[placeArray.length - 1].setMap(null);
                    //removing last object in the place and marker array
                    placeArray.pop();
                    markersArray.pop();
                    //Removing polyline in the map
                    polyline.setMap(null);
                    //function for creating new polyline using the path that does not include the deleted coordinate
                    createPolyline();
                })
    
              
                function createPolyline() {
                 //clearing polyline Path array
                  polylinePath = [];
                 //putting the coordinates in the polylinepath array to be used as the path of polyline
                  for (let i = 0; i < placeArray.length; i++) {
                    polylinePath.push({
                      lat: placeArray[i].lat,
                      lng: placeArray[i].lng,
                    });
                  }
                  
                  //creating polyline
                  polyline = new google.maps.Polyline({
                    path: polylinePath,
                    geodesic: true,
                    strokeColor: "#FF0000",
                    strokeOpacity: 1.0,
                    strokeWeight: 2,
                  })
                  //showing polyline in the map
                  polyline.setMap(map);
                }
                // Adds a marker to the map and push to the array.
                function addMarker(location) {
                  //creating new marker
                  const marker = new google.maps.Marker({
                    position: location,
                    map: map,
                  });
                  //putting the created marker in the markers array to be easily deleted in the map
                  markersArray.push(marker);
                }
              }}
            />
          </div>
        );
      }
    }
    
    export default App;