Import and Export locations on Google Maps

Aneeqa Khan - May 1 - - Dev Community

Hello readers!

Previously I wrote about adding a click function on Google Maps and displaying markers.

Today I want to add another feature in the app by allowing import and export locations.


Create Import and Export Buttons

I added import and export location buttons to the bottom of the web page like this.

{/* displays export and import options */}
  <div className="list-footer">
    <AppButton handleClick={exportLocations}>
      Export Locations
    </AppButton>
    <input
      className="app-button"
      type="file"
      accept=".json"
      onChange={importLocations}
    />
  </div>
Enter fullscreen mode Exit fullscreen mode

Import Locations Logic

This function imports a location list from a JSON file, parses the data, and appends it to the existing list of locations. It utilizes a FileReader to read the file contents and updates the state accordingly.

// Function to import location list from JSON
  const importLocations = (event) => {
    const file = event.target.files[0];
    const reader = new FileReader();
    reader.onload = (e) => {
      const importedData = JSON.parse(e.target.result);
      setListOfLocations([...listOfLocations, ...importedData]);
    };
    reader.readAsText(file);
  };
Enter fullscreen mode Exit fullscreen mode

Export Locations Logic

This function exports the location list as a JSON file by converting the list of locations to JSON format, creating a Blob with the JSON data, and generating a download link for the user to save the file.
Finally, it initiates the download of the JSON file and removes the dynamically created download link from the document.

// Function to export location list as JSON
  const exportLocations = () => {
    const data = JSON.stringify(listOfLocations);
    const blob = new Blob([data], { type: "application/json" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = "locations.json";
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  };
Enter fullscreen mode Exit fullscreen mode

Demo

You can get the full code from my GitHub.


Thank you for reading! Feel free to connect with me on LinkedIn or GitHub.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .