0

In may app I have to show a list of markers and markers that are already stored in sessionStorage, but I cant set markers, zoom and center of the map at first render of the page, I nees refresh the page to see data on it.

FIRST RENDER: enter image description here

AFTER REFRESH: enter image description here

Part of the code is justa above, I have a loadMap where I instaciate map with useLoadScript, I can post it here too if it's necessary!

import React, { useState, useEffect } from "react"
import { GoogleMap, Marker } from "@react-google-maps/api"
import { Trash } from "phosphor-react"
import { useNavigate } from "react-router-dom"

var tempMarker

function Map({
  markers,
  setMarkers,
  wayPoints,
  setWayPoints,
  routeHead,
  setRouteHead,
}) {
  const [isMounted, setIsMounted] = useState(false)
  const [reload, setReload] = useState(false)

  const navigate = useNavigate()
  let marker

  function refreshPage() {
    console.log("passei aqui refresh")
    window.location.reload(false)
  }

  const onChangeMarkers = () => {
    if (markers) {
      if (markers.length > 0) {
        setWayPoints(markers)
        sessionStorage.removeItem("markers")
        sessionStorage.setItem("markers", JSON.stringify(markers))
        if (reload) {
          refreshPage()
          setReload(false)
        }
      }
    }
  }

  useEffect(() => {
    if (!isMounted) {
      setIsMounted(true)
      setReload(false)
      onChangeMarkers()
    }
  }, [])

  const handleOnLoad = (map) => {
    onChangeMarkers()
    const bounds = new window.google.maps.LatLngBounds()
    if (markers) {
      if (markers.length > 0) {
        markers.forEach(({ latitude, longitude }) => {
          let pos = new window.google.maps.LatLng(latitude, longitude)
          bounds.extend(pos)
        })
      } else {
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(
            (position) => {
              const pos = {
                lat: position.coords.latitude,
                lng: position.coords.longitude,
              }
              map.setZoom(13)
              map.setCenter(pos)
            },
            (e) => {
              console.log(e)
            },
            { maximumAge: 15000, timeout: 60000, enableHighAccuracy: true }
          )
        } else {
          let pos = new window.google.maps.latLng()
          pos = { lat: -16.6446324, lng: -49.416115 }
          map.setZoom(10)
          map.setCenter(pos)
        }
      }
    }
    map.fitBounds(bounds)
    map.addListener("click", function (e) {
      placeMarker(e.latLng, map)
    })
  }

  const handleSubmit = async (event) => {
    navigate("/WayPointsTable", { replace: false })
  }

  function placeMarker(location, map) {
    if (marker == null) {
      marker = new window.google.maps.Marker({
        position: location,
        map: map,
      })
    } else {
      marker.setPosition(location)
    }
    const markerId = markers.length
    const markerQtde = markerId + 1
    tempMarker = {
      idRota: routeHead.idRota,
      idVeiculo: routeHead.idVeiculo,
      idFrota: routeHead.idFrota,
      idMotorista: routeHead.idMotorista,
      idAjudante1: routeHead.idAjudante1,
      idAjudante2: routeHead.idAjudante2,
      idAjudante3: routeHead.idAjudante3,
      idCarga: routeHead.idCarga,
      idPonto: markerQtde,
      latitude: parseFloat(marker.getPosition().lat().toFixed(6)),
      longitude: parseFloat(marker.getPosition().lng().toFixed(6)),
      cpfCNPJ: "CPF/CNPJ",
      nome: "PONTO " + markerQtde,
      endereco: "informe o endereco",
      distanciaMinima: "100",
      horarioParada: "00:00",
      dataHoraInicio: routeHead.dtHrInicio,
      dataHoraFim: routeHead.dtHrFim,
      observacao: "",
      valorAReceber: 0,
      custoPernoite: 0,
      idSequencia: markerQtde,
      distanciaEmKm: 1,
      tipoRegistro: "2.ENTREGA",
    }
    console.log(tempMarker)
    markers.push(tempMarker)
    map.setZoom(14)
    let pos = new window.google.maps.LatLng(
      parseFloat(marker.getPosition().lat().toFixed(6)),
      parseFloat(marker.getPosition().lng().toFixed(6))
    )
    map.setCenter(pos)
    setReload(true)
    onChangeMarkers()
  }

  const handleMarkerClick = (evt) => {
    console.log(evt)
  }

  const handleMarkerDrag = (mk, index) => {
    const newLat = parseFloat(mk.latLng.lat().toFixed(6))
    const newLng = parseFloat(mk.latLng.lng().toFixed(6))
    markers = markers.map((marker, i) => {
      if (i === index) {
        marker = { ...marker, latitude: newLat, longitude: newLng }
      }
      return marker
    })
    setMarkers(markers)
    setReload(false)
    onChangeMarkers()
  }

  const handleDeleteMarker = (index) => {
    if (index !== undefined) {
      markers = markers
        .filter((marker, i) => i !== index)
        .map((marker, i) => {
          marker = { ...marker, id: i }
          return marker
        })
      setMarkers(markers)
      setReload(true)
      onChangeMarkers()
    }
  }

  return (
    <div className="flex flex-row">
      <div className="bg-zinc-300 w-1/4">
        <h2 className="text-center text-black font-bold p-2">
          PONTOS DE ENTREGA
        </h2>
        <div className="flex flex-col">
          <div className="overflow-x-auto sm:-mx-6 lg:-mx-8">
            <div className="py-2 inline-block min-w-full sm:px-6 lg:px-8">
              <div className="overflow-hidden">
                <table className="min-w-full">
                  <tbody className="text-black font-semibold">
                    {isMounted &&
                      wayPoints &&
                      wayPoints.length > 0 &&
                      wayPoints.map(({ nome }, index) => {
                        return (
                          <tr key={index}>
                            <td>{index + 1} - </td>
                            <td>{nome.substr(0, 18)}</td>
                            <td>
                              <div
                                key={index}
                                className="inline-block align-middle w-4 bg-red-700 text-white rounded "
                                onClick={() => handleDeleteMarker(index)}
                              >
                                <Trash size={16} alt="Excluir" />
                              </div>
                            </td>
                          </tr>
                        )
                      })}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
        <div className="flex flex-col items-center">
          <button
            onClick={() => handleSubmit()}
            className=" bg-red-500 hover:bg-red-700 py-2 px-4 mt-3 rounded text-zinc-100 font-bold "
          >
            Enviar
          </button>
        </div>
      </div>
      <GoogleMap
        onLoad={handleOnLoad}
        afterLoad={refreshPage}
        mapContainerStyle={{ width: "100vw", height: "100vh" }}
      >
        {isMounted &&
          wayPoints &&
          wayPoints.length > 0 &&
          wayPoints.map(({ nome, idSequencia, latitude, longitude }, index) => (
            <Marker
              key={index}
              position={{ lat: latitude, lng: longitude }}
              title={nome}
              addListener
              draggable
              onClick={handleMarkerClick}
              onDragEnd={(marker) => handleMarkerDrag(marker, index)}
              icon={
                "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=" +
                idSequencia +
                "|FF0000|000000"
              }
            ></Marker>
          ))}
      </GoogleMap>
    </div>
  )
}

export default Map
Fideles
  • 11
  • 8
  • Can you post a codesandbox or a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) that replicates the issue that you're experiencing? So that the community could help you better. – Yrll Dec 07 '22 at 23:08

0 Answers0