Update geographic coordinates using Javascript

I am currently developing a Google Maps feature in a Rails 3.2.12 project. My goal is to update the Latitude and Longitude values through the infoWindow for the location created.

When a user clicks on a marker on the map, an infoWindow will open displaying the location name along with two buttons ("Update" & "Remove"). Upon clicking on the "Update" button, the current infoWindow should close and a new infoWindow should open with latitude and longitude values displayed in text fields.

Please see my code snippet below:

When the "Update" button is clicked, the following function should be called:

function getLocation(){

            currentProjectId = $('#currentProjectId').val();
            sessionId = $('#sessionId').val();
            userId = $('#userId').val();
            var locData = {
                      userId: userId,
                      sessionId: sessionId,
                      command: 'locationUpdate',
                      projectId: currentProjectId
                  };

    markersArray.push(marker);
    currentMarker = marker;
    var infoWindow = new google.maps.InfoWindow();

    google.maps.event.addListener(marker, 'click', function(event){
        infoWindow.close();
        infoWindow.setContent("<p>Location Name:&nbsp; <input id="country" type="text" value='+ address +'></p>\
              <p>Longitude:&nbsp;&nbsp;<input id="lat" type="text" value='+ latitude +'> </p>\
            <p>Latitude:&nbsp;&nbsp;<input id="long" type="text" value='+ longitude +'> </p>\
            <p><input type="button" value="Save" onclick="saveLocation(currentProjectId)"/
             <input type="button" value="Remove" onclick="removeMarker()"/></p>");
        infoWindow.open(map, marker);
    });


    currentMarker = marker;
    var marker = new google.maps.Marker({
        map: Gmaps.map.map,
        position: new google.maps.LatLng(latitude, longitude),
        draggable: true
    });

Answer №1

To extract data from a database and eliminate a specific marker based on its ID, you can implement the following code snippet:

<head>
<script src="js/jquery.js"></script>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDMM9AqbeqIGxanHcZc9Ce3C9rRSRz6qvI&v=3.exp&libraries=places&sensor=false&amp"></script>
    <script>
        var map;
        var marker;
        var center = new google.maps.LatLng(21.0000,78.0000);
        function initialize(){
        var mapProp = {
          center:center,
          zoom:5,
          mapTypeId:google.maps.MapTypeId.ROADMAP
          };

        map =  new google.maps.Map(document.getElementById("googleMap")
          ,mapProp);

        var content = "<input type='button' id='click' value='add marker' />";

        var infowindow = new google.maps.InfoWindow();

        var marker = new google.maps.Marker({
            position:center
        });

        marker.setMap(map);


        google.maps.event.addListener(marker, 'click', function() {

            infowindow.setContent(content);
            infowindow.open(map, marker);


            // currentPopup = null;
        });

     }
    </script>
</head>
<body onload="initialize()">
    <div id="googleMap" style="height:500px; width:550px"></div>

    <script>
        $("body").on("click","#click",function(){
            var mycenter = new google.maps.LatLng(24.0000,78.0000);
            var marker = new google.maps.Marker({
            position:mycenter
        });

            marker.setMap(map);
        var infowindow = new google.maps.InfoWindow();
         infowindow.setContent("am new");
         infowindow.open(map,marker);
        });

    </script>
</body>

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

Updating a section of a webpage using jQuery Mobile

I'm currently facing an issue with modifying a specific section of my webpage. Although this problem has been discussed before, I haven't found a satisfactory solution yet. The element in red on the page needs to change dynamically based on the ...

Show the meta-field mp3 and place it in a lightbox container on the portfolio page

My Current Portfolio Gallery Setup: Currently, my portfolio gallery is displayed in a masonry grid format using the JIG plugin. This grid showcases images from my custom post_type. When clicking on a thumbnail, a lightbox pops up showing the full photo. T ...

Adjust puppeteer window dimensions when running in non-headless mode (not viewport)

Is there a way to adjust the browser window size to match the viewport size in Chrome(ium)? When only setting the viewport, the browser can look awkward if it is not running headfully and I want to visually monitor what's happening within the browser ...

Creating dynamic divs on button click for my project is something that I must do, and I will

When the user clicks on the Add button, a new div should be added as shown in the image above. Implementing this functionality using Bootstrap is crucial because the divs must rearrange correctly based on different resolutions such as 1920x900, 1280x600, ...

Combining strings in a JavaScript object

Can someone help me with concatenating strings within an object in JavaScript? I am parsing through an XML file to create a list of links in HTML. Each time I iterate through the loop, I want to add a new <li> element containing the link. How can I ...

Merging two divs in AngularJS

Currently in the process of converting an application from jQuery to AngularJS, I'm faced with a challenge involving combining two twin beds into a king bed using a bootstrap button toggle. Let's simplify this scenario by imagining two rounded bo ...

Unable to activate function when closing Vuetify v-alert

Is there a way to trigger a function when the Vuetify v-alert is closed? I have explored the documentation but haven't found any information on this specific functionality. In the codepen example, the dismissible attribute allows for closing the alert ...

Sharing the logger object in NodeJS projects: What's the best approach?

After setting up a logger object in the file utils/logger.js using the winston package, I am wondering how to propagate this logger object to all project files (approximately 20 in total). Do I need to include const logger = require('../utils/logger&a ...

Velocity.js causing a slowdown in animated performance

Currently, I am attempting to animate spans, and while the animation is functional, it appears to be somewhat choppy and lacks smoothness. https://codepen.io/pokepim/pen/JBRoay My assumption is that this is due to my use of left/right for animation purpos ...

Is there a way to stop myself from accidentally clicking twice on the same tile?

I'm currently working on a game and facing an issue where my "X" gets deleted when clicking twice on the same tile. I am able to move my "X" around, but the double-click deletion is causing trouble. I attempted using booleans but struggle with them. I ...

Express.js never terminates a session

I have a Backbone View that makes an Ajax call to the server to delete a session. Upon triggering the following event on the server: app.delete('/session', function(req, res) { if (req.session) { req.session.destroy(function() { ...

Trouble encountered when transmitting JavaScript array through AJAX to Laravel

I am encountering an issue with sending a JavaScript array to a controller via an AJAX GET method. Here is the structure of my JavaScript: var requestData = JSON.stringify(commentsArray); console.log(requestData); //I can see the correct JSO ...

What could be causing the User object in the auth0/nextjs useUser hook to have missing properties?

The user object retrieved using the useUser hook from auth0/nextjs package seems to be missing some important properties: { "nickname": "example", "name": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bedbc6dfd3ced2dbfec7 ...

Is there a way to make the fixed table header scroll along with the table body data?

I am facing an issue with my table where I have multiple columns. I have managed to fix the table header successfully, however, when I scroll horizontally through the table body columns, the header remains fixed and does not move accordingly. How can I res ...

An alternative method to confirm the checkbox selection without physically clicking on it

Currently, I'm in the process of creating a basic to-do list and have been attempting to connect the task with its corresponding checkbox. My goal is for the checkbox to automatically be checked when the task is clicked. Instead of using HTML to add ...

When loading HTML using JavaScript, the CSS within the HTML is not properly processing. Leveraging Bootstrap 5 might help resolve

Currently utilizing bootstrap 5 for my project. I have a setup in index.html where I am loading the contents of nav.html using JavaScript. However, I am facing an issue wherein the CSS styling for the navbar is not being applied when loaded via JS. Strange ...

The animation for the login and registration modal is malfunctioning and not functioning as

I am currently working on implementing a login/register modal in React, inspired by a TypeScript example I came across. This is how the login section looks: https://i.sstatic.net/ECvv9.png The goal is to: When the "Sign up" button is clicked, it should ...

Encountering an issue when attempting to save JSON data in the database: unable to convert object into a string

To summarize, my data is stored in Javascript: JSONdata = { name: form.name.value, address1: form.custa.value, address2: form.custa2.value, postcode: form.custpc.value, order: fullorder, cost: document.getElementById('total&ap ...

What could be causing the Uncaught ReferenceError message that says scrollToM is not defined in my code?

Can someone help me with this code for creating a single page website? $(window).load(function() { function filterPath(string) { return string .replace(/^\//,'') .replace(/(index|default).[a-zA-Z]{3,4}$/,'') ...

Enhance user experience with AngularJS Bootstrap autocomplete feature by automatically filling input box when hovering over dropdown options

I am currently implementing the AngularJs Bootstrap typeahead functionality. Typically, when we enter text that matches an option, the dropdown list appears. https://i.stack.imgur.com/395Ec.png What I aim for is to automatically fill the textbox with the ...