ReactJS issue with form, location data and google maps API

18 views Asked by At

I have an issue with a code I'm developing for a personal project. I'd like to create a form in ReactJS where users can input a variable number of addresses. I want these addresses to autocomplete using the Google Maps API. Once a user selects an address, I want it to display as a marker on a Google Maps map. The problem I'm encountering is that after I select one of the autocomplete suggestions and add a new address, the autocompleted addresses get erased, leaving only the part typed by the user. Additionally, I'm having trouble storing the lat and lng for each address (I want to send the autocompleted addresses and their corresponding lat and lng to one server I have deployed). I am having issues with the marker rendering as well.

Furthermore, for compatibility reasons, the only library that has worked for me is @react-google-maps/api.

Any suggestions? Thanks in advance! I put the code I have already done

import React, { useState} from 'react';
import axios from 'axios';
import { GoogleMap, LoadScript, Autocomplete, Marker } from '@react-google-maps/api';
import { google_maps_api_key } from './config_google_maps';

// Define las bibliotecas como una constante fuera del componente
const libraries = ["places"];

const api = axios.create({
  baseURL: 'http://127.0.0.1:5000',
  headers: {
    'Content-Type': 'application/json',
  },
});

const Optimizer = () => {
  const [addresses, setAddresses] = useState([{ value: '', selectedAddress: '' }]);
  const [markers, setMarkers] = useState([]);
  const [selectedAddress, setSelectedAddress] = useState('');

  const onAddressChange = (index, value) => {
    setAddresses((prevAddresses) => {
      const updatedAddresses = [...prevAddresses];
      updatedAddresses[index].value = value;
      return updatedAddresses;
    });
  };

  const onAddressSelect = (index, address, latLng) => {
    const newMarkers = [...markers];
    newMarkers[index] = latLng;
    setMarkers(newMarkers);
    setAddresses((prevAddresses) => {
      const updatedAddresses = [...prevAddresses];
      updatedAddresses[index].selectedAddress = address;
      return updatedAddresses;
    });
  };

  const addAddress = () => {
    setAddresses([...addresses, { value: '', selectedAddress: '' }]);
  };

  const removeAddress = (index) => {
    const newAddresses = [...addresses];
    newAddresses.splice(index, 1);
    setAddresses(newAddresses);

    const newMarkers = [...markers];
    newMarkers.splice(index, 1);
    setMarkers(newMarkers);
  };

  const sendToServer = () => {
    // Create an array with the addresses and associated lat/lng
    const dataToSend = addresses.map((address, index) => ({
      address: address.selectedAddress,
      lat: markers[index]?.lat || null,
      lng: markers[index]?.lng || null,
    }));

    // Send data to the server using axios or your preferred HTTP library
    api.post('http://127.0.0.1:5000', dataToSend)
      .then(response => {
        // Handle the response from the server
      })
      .catch(error => {
        // Handle errors
      });
  };

  return (
    <div className='background'>
      <div className="container">

        <div className="next-section">
        </div>

        <LoadScript googleMapsApiKey={google_maps_api_key} libraries={libraries}>
          <GoogleMap
            mapContainerStyle={{ height: '400px', width: '100%' }}
            center={{ lat: 0, lng: 0 }}
            zoom={2}
          >
            {markers.map((latLng, index) => (
              <Marker key={index} position={latLng} />
            ))}
          </GoogleMap>

          <button onClick={addAddress}>Add Address</button>

          {addresses.map((address, index) => (
            <div key={index}>
              <Autocomplete
                onPlaceSelected={(place) => onAddressSelect(index, place.formatted_address, place.geometry.location)}
              >
                <input
                  type="text"
                  value={addresses[index].value}
                  onChange={(e) => onAddressChange(index, e.target.value)}
                  placeholder="Enter an address"
                />
              </Autocomplete>
              <button onClick={() => removeAddress(index)}>Remove</button>
            </div>
          ))}

          <button onClick={sendToServer}>Send to Server</button>
        </LoadScript>
      </div>
    </div>
  );
};

export default Optimizer;

I've tried switching libraries, but for compatibility reasons, the only one that works for me and doesn't give me errors is @react-google-maps/api. On the other hand, I've tried to save the lat-lng separately, but I don't understand how to do it.

0

There are 0 answers