Can anyone show me how to place a marker at the exact location where I click on a map using the React/Nextjs

Need help figuring out how to place a marker on a map when clicking on a location, while also deleting the previous marker. Here's the code snippet I'm working with:

const guessCoords = null;

const handleMapClick = (e) => {
  let lat = e.latLng.lat();
  let lng = e.latLng.lng();
  guessCoords = { lat, lng };
};

function Map() {
  const center = useMemo(() => ({ lat: 44, lng: -80 }), []);

  return (
    <GoogleMap
      zoom={10}
      center={center}
      streetView={false}
      mapTypeId="roadmap"
      mapContainerClassName="w-full h-full absolute"
      mapTypeControls={false}
      onClick={(e) => handleMapClick(e)}
    >
      <Marker position={guessCoords} />
    </GoogleMap>
  );
}

Developing in NextJS and struggling to find a solution for my specific scenario.

Answer №1

Initially, I intended to leave a comment on your query rather than an answer, however, due to restrictions on stackoverflow, I am providing my assistance in this manner!

Which component are you utilizing for the Google Maps integration? Personally, I suggest using google-map-react as it has worked seamlessly for us.

I advise you to address your typescript code! guessCoords should not be declared as const since it is modified within your click method. Here's the corrected version of the code snippet in typescript:

let guessCoords;

const handleMapClick = (e) => {
  const lat = e.latLng.lat();
  const lng = e.latLng.lng();
  guessCoords = { lat, lng };
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What steps can I take to ensure that my React child components will render successfully, even if a prop is absent

TLDR; Seeking solution to render child components in React even if a property of this.props is missing. My React app utilizes Yahoo's Fluxible and fetches data from a Wordpress site using WP REST API. Sometimes, the API may return incomplete data cau ...

Tips on updating the text of markers in ng-map from 'A' to 'B' and vice versa

Looking to customize ng-map markup to display "start" and "end" instead of "A" and "B." Referenced this resource, but encountered issues displaying both "start" and "A" in the markup. Noticing a discrepancy in the distance between the source and destinat ...

Event on FullCalendar is directing to an incorrect URL

After integrating FullCalendar to my website following a tutorial, everything seems to be working fine except for the URLs added to events on the calendar. Instead of directing me to the specified URL when I click on an event, it redirects me to a differen ...

What causes the server to give an incorrect response despite receiving a correctly read request?

After setting up a new project folder and initializing NPM in the Node.js repl, I proceeded to install the Express package. In my JavaScript file, I included the following code: const express = require('express'); const app = express(); ...

Laravel: JavaScript Integration Problem (Current Status Concern)

I encountered an issue with the update status feature. The status is being stored correctly in the database, but the corresponding status icon does not change as expected. Upon refreshing the page, the status icon reverts to its previous position, even tho ...

What is the significance of using curly braces within the function setFormData to update the formData object with the key-value pair [e.target.name]: e

The onChange function I have set up is used for submitting a form with multiple input values, and it takes in whatever the name attribute of the input field is. While I understand the basic functionality of this code, I am curious about what exactly happen ...

Choosing a class using Jquery through a For loop in Javascript

I have a group of images with a class applied to them. I am attempting to create a for loop that will iterate through the elements of this class. In Python, you can use "for element in thing" and I was curious if there is something similar in JavaScript. A ...

show certain DIVs based on the URL

Is it possible to dynamically display different sections based on the URL? My event website has 3 subevents, and I'd like to show the date of each event in the navigation bar for their respective URLs. <div id="us" class="us-web-date">&nbs ...

extract data from a JSON object

I am in possession of the JSON data shown below: [ { "AVG_VALUE" : "2540", "MAX_VALUE" : "2540", "SUM_VALUE" : "2540", "MIN_VALUE" : "2540", "METRICID" : "100248060212", "START" : "1449216120000", "STARTTIME" : "09:02" } , { ...

Do I need to use the "--save" flag in npm to add dependencies to the "package.json" file?

Do I really need to use the "--save" flag in order to add an installed dependency to the "package.json" file? I conducted a test without the "save" flag and found that the package was still added to the "dependencies" section. It seems like it is the defa ...

Utilize a button within a form to add additional variables to a URL that already contains variables from a separate form

I operate a website that features a search bar and checkboxes for adding variables to the URL: term = "test" variable1=1 url/search?term=test&variable1=1 After completing the initial search, I have additional forms on the left side of the page with m ...

Having trouble getting all buttons to update at once? When using JavaScript and AJAX, only the first button seems to get updated

I have successfully developed my own custom "like" button feature. Utilizing AJAX, I can seamlessly update the database to increment the "like" count by 1. Subsequently, JavaScript handles the task of updating the first "like" button with the revised infor ...

Error: The data object does not support the filter function

My current task involves filtering an array of JSON objects obtained from an API call through my proxy. The API call is made using the Node.js web framework Express. The API response looks like this: { data: [ { type: "aaa", name: "Cycl ...

What is the best method for capturing the current CSS settings?

For my web project, I am implementing jQuery drag and drop features as well as resizing elements. However, it's frustrating because every time I close the browser or refresh the page, all my progress is lost. To avoid this issue, I want to save the en ...

Automatically populate text fields depending on the option chosen from the drop-down menu

I'm currently developing a .asp webpage using JavaScript as the scripting language. One of the features I have is a drop-down menu with options populated from an 'agencies' table in the database. The 'agencies' table includes vario ...

Customize React Hook Form version 7 by incorporating a unique input method for handling empty values

Introducing my custom Input component: export type InputProps = { error?: string } & InputHTMLAttributes<HTMLInputElement> export const Input: FunctionComponent<InputProps> = ({ error, ...props }) => ( <input {...props} /> ) ...

The body of the POST request appears to be void of any

Whenever I make a request using curl or hurl, an issue arises. Despite req.headers['content-length'] showing the correct length and req.headers['content-type'] being accurate, req.body returns as {}. Below is the Hurl test: POST http:/ ...

Incorporating an express server into the vue-webpack-boilerplate for enhanced functionality

Recently, I got my hands on the vue-webpack-boilerplate from GitHub, and so far, it seems pretty impressive! This is my first time working with webpack and ESlint, so I'm eager to learn more. However, I have a question about integrating an express ba ...

JavaScript code to record the time when a client exits my website by clicking the X button in the top right corner and save it in my database

I need to record in the database the times when users enter and exit my site. Saving the entry time is not an issue, nor is saving the exit time by clicking my "log off" button. However, what about when a client exits by clicking the X in the right corner ...

Retrieve the parent ID value using a jQuery click event

I am trying to retrieve the parent div id of a clicked button. The parent div will have a class of .jsgrid. However, my current solution using rootParentId is returning undefined. I believe I may have overlooked something. Can someone help me figure this ...