I need help creating a Google marker using the Maps JavaScript API

I am currently working with the Google Maps API. The map displays the latitude and longitude when a mouse click event occurs. My next step is to add a Google marker to the map. Below is my JavaScript code snippet:

<script>
      function initMap() {
        var myLatlng = {lat: 23.133899799999995, lng: 14.812842999999999};

        var map = new google.maps.Map(
            document.getElementById('map'), {zoom: 16, center: myLatlng});

        // Create the initial InfoWindow.
        var infoWindow = new google.maps.InfoWindow(
            {content: 'Click the map to get Lat/Lng!', position: myLatlng});
        infoWindow.open(map);

        // Configure the click listener.
        map.addListener('click', function(mapsMouseEvent) {
        // Close the current InfoWindow.
        infoWindow.close();

        // Create a new InfoWindow.
        infoWindow = new google.maps.InfoWindow({position: mapsMouseEvent.latLng});
        infoWindow.setContent(mapsMouseEvent.latLng.toString());
        infoWindow.open(map);
        
          //Display latitude and longitude on the webpage
        var l =mapsMouseEvent.latLng.toString();
        document.getElementById("latlng").innerHTML=l;
        
        });   
      }
    </script>

Answer №1

For an illustration on how to add markers, take a look at this example: https://developers.google.com/maps/documentation/javascript/examples/marker-simple

var marker;
// Setting up the click listener.
map.addListener('click', function(mapsMouseEvent) {
  // Close the current InfoWindow.
  infoWindow.close();

  if (marker && marker.setPosition)
    // If there is already a marker, move it
    marker.setPosition(mapsMouseEvent.latLng);
  else
    // Create a blue marker
    marker = new google.maps.Marker({
      position: mapsMouseEvent.latLng,
      map: map,
      icon: "http://maps.google.com/mapfiles/ms/micons/blue.png"
    });
 });

https://i.sstatic.net/gsEsv.png

function initMap() {
  var myLatlng = {
    lat: 23.133899799999995,
    lng: 14.812842999999999
  };

  var map = new google.maps.Map(
    document.getElementById('map'), {
      zoom: 16,
      center: myLatlng
    });
  var marker;
  // Creating the initial InfoWindow.
  var infoWindow = new google.maps.InfoWindow({
    content: 'Click the map to get Lat/Lng!',
    position: myLatlng
  });
  infoWindow.open(map);

  // Setting up the click listener.
  map.addListener('click', function(mapsMouseEvent) {
    // Closing the current InfoWindow.
    infoWindow.close();

    if (marker && marker.setPosition)
      marker.setPosition(mapsMouseEvent.latLng);
    else
      marker = new google.maps.Marker({
        position: mapsMouseEvent.latLng,
        map: map,
        icon: "http://maps.google.com/mapfiles/ms/micons/blue.png"
      });

    // Displaying latitude and longitude on the site
    var l = mapsMouseEvent.latLng.toString();
    document.getElementById("latlng").innerHTML = l;

  });
}
html,
body {
  height: 100%;
  width: 100%;
  padding: 0px;
  margin: 0px;
}

#map {
  height: 90%;
  width: 100%;
}
<div id="latlng"></div>
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>

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

Is there a way to make my red div switch its background color from red to green when I press the swap button?

How can I make the red div change its background color to toggle between red and green when I click on the swap button in the following code? $(document).ready(onReady); var numberOfClicks = 0; function onReady() { console.log('inside on ready ...

Utilizing ReactJS to retrieve configuration settings from a YAML file, similar to how it is done

Our team is currently using a full-stack multi-microservice application where the backend java components utilize the spring @value annotation to fetch configuration values from a yml file. This method has been effective and even the Java side of our UI c ...

Implementing Shader Effects around Mouse using Three.js

Could someone please share tips on how to add a shader effect around the mouse area using Three.js? I'm inspired by the homepage of this website: I'm eager to explore some leads or examples. Thank you in advance! ...

Effortless method of organizing information like scores

I have developed a multiplayer game that will be played on a server, and I need to save the high scores of the players. These stored scores should be consistently available and easily accessible for all players at any time. Can anyone suggest a good appro ...

Using PHP/JavaScript to activate a button once the timer reaches 00:00

I came across a JavaScript fiddle code that is working perfectly. Here it is: HTML <div id="worked">00:05</div> JS $(document).ready(function (e) { var $worked = $("#worked"); function update() { var myTime = $worked.h ...

The HTML content retrieved through an ajax service call may appear distorted momentarily until the JavaScript and CSS styles are fully applied

When making a service call using ajax and loading an HTML content on my page, the content includes text, external script calls, and CSS. However, upon loading, the HTML appears distorted for a few seconds before the JS and CSS are applied. Is there a sol ...

Suggestions for relocating this function call from my HTML code

I have been working on updating a javascript function that currently uses an inline event handler to a more modern approach. My goal is to eliminate the unattractive event handler from the actual HTML code and instead place it in a separate modular javascr ...

combining the package.json files of the client and server into a single file

I need assistance with merging server-side code (in nodejs) and client-side code (with react) into a single package.json file. The server file is located in the project root directory, while the client-side code resides in the /client folder along with oth ...

What is the reason the useEffect hook does not function properly with a state variable within context?

Check out my code here. I'm trying to display the content of the array testingData, but it's not showing up. If I remove the useEffect hook, it works fine. Can you help me understand why and how to fix it? ...

Tracking the last time an app was run in Javascript can be achieved by creating a variable to store the date when

Exploring the world of Javascript as a newbie, I find myself with index.html, stylesheet.css and div.js in my app. Within div.js lies a code that magically generates a schedule for our team members over 2 weeks. However, there's a catch - consistency ...

Check for duplicates within 2 arrays by implementing a filtering process

I am trying to figure out how to compare two arrays to determine if there are any duplicates within them. const result = this.specialRange.filter(d => !dayMonth.includes(d)); What I have attempted so far just returns the entire array back to me, but I ...

What could be causing the misalignment of the Datepicker calendar in Material UI?

I have integrated a datepicker using the library "@mui/x-date-pickers/DatePicker". import { DatePicker } from "@mui/x-date-pickers/DatePicker"; import { AdapterMoment } from "@mui/x-date-pickers/AdapterMoment"; import { Locali ...

What causes a function loss when using the spread operator on window.localStorage?

I am attempting to enhance the window.localStorage object by adding custom methods and returning an object in the form of EnhancedStorageType, which includes extra members. Prior to using the spread operator, the storage.clear method is clearly defined... ...

Issue with Reactive Form - The call signatures of 'FormGroup' are not compatible

I have a function written in TypeScript: // Form summaryAreaForm = new FormGroup ({ summary: new FormControl(null) }) // Function update() { document.getElementById('textDiv').innerHTML = this.summaryAreaForm('summary').value ...

Setting a fixed time for a preloader is a simple and effective way to

Is there a way to specify a specific duration for the preloader on my website? I find that after the images have preloaded, I am unable to see any animations in the home section. $(window).load(function() { $('#preloader').fadeOut( ...

Discover the seamless process of dynamically adjusting metadata to reflect current state values within the Next.js app directory

Exploring the app directory within Next.js version 13, I came across a change in the official documentation where they have replaced the old head method with metadata. Initially, I thought this feature was only available on page or layout components. Now, ...

Guide to automatically choose the first item and emphasize the chosen selection in AngularJs

I am currently developing an app that showcases a list of items on the left side. By default, the first item is highlighted and its details are displayed on the right side. When a user clicks on any item in the list, that item should be highlighted and its ...

Mongoose - Child Subdocument with References to Parent Schema

Could a Mongoose Schema be structured similar to this example: var categorySchema = new Schema({ name : String }); var childSchema = new Schema({ name : String, category : { type : Schema.Types.ObjectId, ref : 'parent.categori ...

Using Meteor methods in a Meteor and Ionic application: A guide

After building the web app with Meteor, I am now looking to develop a new app utilizing both Meteor and Ionic technologies. My goal is to leverage the existing Meteor methods in my Ionic app without duplicating efforts for mobile development. Any suggestio ...

struggling with toggle functionality

I am encountering an issue with a list in jQuery where toggling between slim and wide side menus is affecting multiple menu items instead of just one. The toggle should only occur when the user clicks on a specific class, the "toggle-button-on" menu. How ...