What is preventing me from retrieving the coordinates from the marker in the Google Maps Places API?

Is there a way to obtain the latitude and longitude from a marker in google maps when it is relocated to another position?

I have researched and located the solution, however, I seem to be encountering an issue. While I can successfully retrieve the coordinates when selecting a search result address, the problem arises when dragging and dropping the marker to a new location...the coordinates remain unchanged.

    <script>

  function initMap() {
    var map = new google.maps.Map(document.getElementById('map'), {
      center: {lat: 38.241997, lng: 21.736244},
      zoom: 13
    });
    var card = document.getElementById('pac-card');
    var input = document.getElementById('pac-input');
    var types = document.getElementById('type-selector');
    var strictBounds = document.getElementById('strict-bounds-selector');

    map.controls[google.maps.ControlPosition.TOP_RIGHT].push(card);

    var autocomplete = new google.maps.places.Autocomplete(input);

    // Bind the map's bounds (viewport) property to the autocomplete object,
    // so that the autocomplete requests use the current map bounds for the
    // bounds option in the request.
    autocomplete.bindTo('bounds', map);

    // Set the data fields to return when the user selects a place.
    autocomplete.setFields(
        ['address_components', 'geometry', 'icon', 'name']);

    var infowindow = new google.maps.InfoWindow();
    var infowindowContent = document.getElementById('infowindow-content');
    infowindow.setContent(infowindowContent);
    var marker = new google.maps.Marker({
      map: map,
  draggable: true,
      anchorPoint: new google.maps.Point(0, -29)
    });

google.maps.event.addListener(marker, 'dragend', function() {
document.getElementById('Lat').value = marker.getPosition().lat();
    document.getElementById('Lng').value = marker.getPosition().lng();
});

    autocomplete.addListener('place_changed', function() {
      infowindow.close();
      marker.setVisible(true);
      var place = autocomplete.getPlace();
  document.getElementById('Lat').value = place.geometry.location.lat();
      document.getElementById('Lng').value = place.geometry.location.lng();

      if (!place.geometry) {
        window.alert("No details available for input: '" + place.name + "'");
        return;
      }

      // If the place has a geometry, then present it on a map.
      if (place.geometry.viewport) {
        map.fitBounds(place.geometry.viewport);
      } else {
        map.setCenter(place.geometry.location);
        map.setZoom(17);  // Why 17? Because it looks good.
      }
      marker.setPosition(place.geometry.location);
      marker.setVisible(true);


      var address = '';
      if (place.address_components) {
        address = [
          (place.address_components[0] && place.address_components[0].short_name || ''),
          (place.address_components[1] && place.address_components[1].short_name || ''),
          (place.address_components[2] && place.address_components[2].short_name || '')
        ].join(' ');
      }

      infowindowContent.children['place-icon'].src = place.icon;
      infowindowContent.children['place-name'].textContent = place.name;
      infowindowContent.children['place-address'].textContent = address;
      infowindow.open(map, marker);
    });


    document.getElementById('use-strict-bounds')
        .addEventListener('click', function() {
          console.log('Checkbox clicked! New state=' + this.checked);
          autocomplete.setOptions({strictBounds: this.checked});
        });
  }



</script>

I then populate the coordinates in two form inputs (Lat and Lng), which works perfectly with place_changed events. However, when it comes to dragging and dropping the marker, the functionality does not execute. Thank you for your assistance.

Answer №1

Utilize the following code snippet to retrieve GPS coordinates:

let latitude = location.geometry.position.lat();
      let longitude = location.geometry.position.lng();
      let locationName = location.name;

      alert("Latitude: "+latitude+ "___Longitude: "+longitude + " Location: "+locationName);

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

Chrome is experiencing a problem with anchor tags that have an href attribute set to a "blob:" URL and using a target of "_blank"

My current project involves developing a website feature that allows users to download a PDF version of a page. To achieve this, the generated HTML is rendered into a PDF on the server, which is then returned as a Base64-encoded PDF. This data is converted ...

How to prevent table row from highlighting on hover in Angular Bootstrap

In my project, I have a table that showcases various details and allows users to select certain rows. Some of these rows have child rows which can also be selected. The requirement is for the parent rows to be selectable only if they do not have any child ...

Getting the highest level object in a nested Angular component structure

Currently, I am in the process of developing a query builder using Angular that bears resemblance to the JQuery builder. However, I have encountered an issue related to emitting the data. Whenever I click on the addGroup or addRule buttons, a new group is ...

How do I ensure my object is fully constructed before sending it in the response using NodeJS Express?

Currently, I am in the process of constructing a result_arr made up of location objects to be sent as a response. However, my dilemma lies in figuring out how to send the response only after the entire array has been fully constructed. As it stands, the re ...

What is the best way to ensure all JavaScript is fully executed on a webpage before utilizing Selenium with Python?

As I work on my webpage, I am using Selenium with Python to locate specific elements within it. However, a challenge that I am facing is that the elements I need are dynamically generated through JavaScript. Upon examining the page source provided to my S ...

Move the alt attribute from the image to the paragraph text using jQuery or JavaScript and replace it

Struggling to crack the code conundrum that has been taunting me for what seems like an eternity! <div id="slider"> <ul> <!-- --> <li><a target="_blank" href="ANOUK-2014-De-l ...

Utilize buttons to send data to a PHP script

Currently, I am in the process of developing a control panel for an application, consisting of an array of buttons. My aim is to relay information about the specific button pressed to the designated script responsible for executing commands. However, I am ...

Learn how to rearrange the order of Vue elements

I am working with a specific object structure in my code: lines: [{ order: '1', text: ' blue' },{ order: '2', text: 'green' },{ order: '3', text: 'yellow' }] Currently, thi ...

Implement a transition effect for when elements change size using the `.resizable().css` method

I attempted to incorporate a deceleration effect when resizing an element back to its original size using the resizable method. The slowdown effect should only trigger during the click event (when the "Click-me" button is pressed), not while manipulating ...

A handy tool for easily previewing JavaScript code based on my TypeScript within Visual Studio

Recently I decided to dive into TypeScript. I am eager to find extensions for VisualStudio or Re# that can display live JavaScript based on the TypeScript code I write. Any suggestions for tools like this? Currently, I am using VS 2015 with Re#. ...

I am unsure how this type of jQuery AJAX data : () will be interpreted

I'm not a beginner nor an expert in jQuery. I'm modifying a jQuery code for opencard checkout section. There is a Javascript file in this section that sends data to the server. I came across an AJAX request with data structured like this: url: ...

Which event occurs first for a4j:jsFunction, reRender or oncomplete?

After running a jsFunction, I want the javascript to execute once the re-rendering is completed. I assume that the "oncomplete" javascript function is triggered after the re-rendering process, but I'm not entirely certain. Any insights on this? Appre ...

Loading Vue bootstrap b-form-select initially triggers Vuelidate's $anyDirty to become true

My current issue arises from the input event triggering when I initially assign a value to the v-model. This data is fetched via an API, causing the form to be marked as dirty due to the change. However, this poses a problem in another component where the ...

"Enhance the functionality of material-table by incorporating a multi-select feature

My data management has been made easier with Material-Table, but I have encountered a small issue. The code below shows how I currently get a select menu for my data. However, I am looking to have a multiselect menu instead, allowing me to save more than o ...

No specific path has been established for the key auths

I am currently working on a project that involves using react-native-router-flux for navigation. However, I am encountering an error. https://i.sstatic.net/vE1c9.png This is my Router setup: <Router navTransparent> <Lightbox> ...

``Please note that the Sinon spy.called method is currently not

Context In my setup, a small server receives data from a machine. Each time a message is received, a function in a dispatcher object is called, which simply logs everything it receives to the console. Issue While I can see the logs in the console, Sinon ...

"When setting up a window.EventListener, the Div element fails to be hidden when setting its display property to 'none

I'm working on creating a preloader by displaying an overlay until all the content on the page is loaded. However, despite checking my code multiple times, I can't seem to figure out why it's not working. If anyone could provide some assist ...

An error occurred due to a TypeError: attempting to instantiate a new Clock object, but 'Clock' is undefined and not a constructor

Following an update from react native project version 0.63 to 0.72.4, I encountered an issue related to the material tab ( "@react-navigation/material-top-tabs": "^6.6.5") library. Everything was working fine initially, but now I am facing an error on a sp ...

The Vue application is unable to expand to 100% height when using a media query

Hello everyone, I'm currently using my Vue router for multiple pages, and I'm facing an issue where setting the height of the main container to 100% within this media query is not working as expected: @media screen and (min-width: 700px) { #sig ...

Creating a button that redirects to an external link in CodeIgniter:

Hello everyone, I'm new here and I could really use some assistance with a problem. I am trying to link the button labeled 'lihat rincian' and each row of tables to redirect to an external link like Here's a snapshot of my datatables ...