Refresh the location markers on Google Maps API to reflect their current positions

I'm currently in the process of learning how to utilize JavaScript with Rails, and I'm encountering some challenges when it comes to updating my markers based on my current position using AJAX. I suspect that the 'ready page:load' event is not triggering the updated coordinates stored as a data-attribute called 'coords' since the page isn't actually refreshing. How can I leverage my current position data and incorporate longitude/latitude values into events for updating?

var map; 

$(document).on('ready page:load', function() {
 if ("geolocation" in navigator) {
    myMap.init();

    var coords = $('#map-canvas').data('coords');

    if (coords){
        myMap.addMarkers(coords);
    }
 }
});

myMap.init = function() {
 if(navigator.geolocation){

  var mapOptions = {
    zoom: 14,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

 map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

 navigator.geolocation.getCurrentPosition(function(position){

    var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
    var infoWindow = new google.maps.InfoWindow({
        map: map,
        position: pos
    });

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

    map.setCenter(pos);

    var latitude = position.coords.latitude;
    var longitude = position.coords.longitude;  

    $.ajax({
        url:"/all_events",
        method: "GET",
        data: {
            latitude: latitude,
            longitude: longitude
        },
        dataType: 'script'
    });
});

} else {
    document.getElementById('map-canvas').innerHTML = 'No Geolocation Support.';
}

};

myMap.addMarkers = function(coords){

var image = "http://maps.google.com/mapfiles/ms/icons/yellow-dot.png"

coords.forEach(function(coord){
    var myMarker = new google.maps.Marker({
        position: new google.maps.LatLng(coord.latitude, coord.longitude),
        map: map,
        icon: image
    });
});
}

Answer №1

To ensure your script functions correctly as desired, it is recommended to follow these steps:

  • Wrap your foreach loop in a function and execute it after each AJAX callback.
  • Ensure that the AJAX is triggered only after the Google Maps have fully loaded. If the Google Maps library is not fully loaded, you may encounter issues creating a Google LatLng object, which could be the issue in this case.

I trust this guidance will be beneficial.

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 methods can be used to control the URL and back button in a web application designed similar to an inbox in Gmail?

Similar Question: Exploring AJAX Techniques in Github's Source Browser In my application, there are essentially 2 main pages: The main page displays a list of applications (similar to an inbox) The single application page is packed with various ...

Combining React state value with an HTML tag would be a great way

I am facing an issue while trying to concatenate the previous value with new data fetched from an API using a loop. Instead of getting the desired output, I see something like this: [object Object][object Object],[object Object][object Object] Here is ...

Finding differences between two 24-hour format times using moment.js

Is there a way to compare two times in 24-hour format using the code below? $("#dd_start_timing, #dd_end_timing").on('keyup change keydown', function() { var DutyDayStartTime = $("#dd_start_timing").val().trim();// 13:05 var ...

What is the best way to modify an Li element using the DOM in JavaScript?

Just the other day, I discovered how to use JavaScript and DOM to add and delete Li elements. Now I'm curious about how to edit those Li elements using DOM. Any suggestions? Thank you! ...

When I try to import script files into my ASP.NET page, Intellisense displays the methods accurately. However, when I attempt to call one of them, an

I added a function to an existing .js file (I tried two different files) in order to make the method accessible in multiple locations without having to repeat the code. I also created a simple function just to confirm that my function wasn't causing a ...

What are the steps for defining the maximum and minimum values in AngularJS?

I'm working with the following HTML markup: <div class="input-group-icon">Max <span class="error">*</span> <div class="input-group"> <input style="border-right:none;" name="available_funds_max" ng-model="attributes.avai ...

Avoid using fs.read without returning a value to console.log

Seeking assistance with parsing a text file named information.txt and displaying the values using console.log. Here is the code snippet: fs.readFileSync("information.txt", "utf-8", function (err, data) { ...

Extract data from Markit On Demand API using JavaScript and AJAX

I'm struggling to properly parse the response from the API. While I can retrieve the entire response, I am a bit lost on how to effectively parse it. Below is my code snippet: <!DOCTYPE> <html> <head> <style> img ...

How can I execute a jQuery function at the conclusion of a callback?

I am struggling to grasp the concept of jQuery asynchronous execution. The issue I am facing involves a function that updates a select list. Here is the code snippet: function loadGroups() { $.getJSON("/Process/ShowGroups", null, function (data) { va ...

The server appears to be active, but there is a lack of content rendering when using React, Node

When I attempt to run the code in app.jsx, nothing displays even though the index.html is functioning properly. Code from Server.js: var express = require('express'); server.js page var app = express(); app.use(express.static('public' ...

Implementing OPTIONS request header support in an aspx page

Currently, I am working on a service that can handle form posts. While adding support for CORS requests, I encountered an issue in Firefox 3.6 where it sends a preflight request with an OPTIONS request header. Though I managed to add the necessary Access- ...

Stopping all subsequent functions if a condition is false or null can be achieved by implementing an abort

I have implemented a couple of ajax scripts in my code to manage user existence checks and user creation. The first ajax call is intended to verify if the user exists, while the second call aims to create the user if they do not exist. Although the ajax.d ...

Troubleshooting a jQuery ajax error when sending data variables

Hey there, just a quick question for you: var h = $('#hebergeurJQUERY').val(); var t = $('#typeJQUERY').val(); function requestData() { $.ajax({ type: "GET", url: '12months/months.php', data : "hosting= ...

Why does the for loop function correctly with console.log but not with innerHTML?

Hello! I'm completely new to JavaScript, so please excuse any oversight... Below is the code that runs when a button on the page is clicked: function getNumbers() { var firstValue = document.getElementById("time_one").value; var ...

Success message displayed for Ajax form submission, yet email delivery remains pending

In my PHP code for sending emails, I have a function called "Send to friend" that works perfectly with standard PHP post. This confirms that the sendtomail.php file is functioning correctly as well. /* AJAX Code for Send to Friend */ $(function() { $(&ap ...

What is the process for determining the total of elements within an array?

Imagine you have the following array: const items = [ { "amount1": "100", "amount2": "50", "name": "ruud" }, { "amount1": "40", "amount2": "60", "name": "ted" } ] Your goal is to calculate the sum of all amount1 and amount ...

The discrepancy in the array leads to a result of either 1 or an undetermined

Array x = [3,5,7,9,1] Array y = [3,7,8] z = x - y this should result in z = [5,9,1] (7 is common but I want it excluded) Below is the code snippet: function arrayDifference(x, y) { var arr = []; var difference = []; for (var i = 0; i<x.length& ...

Having trouble with CSS and javascript files not resolving after moving app to a new Windows 7 development machine

I have recently migrated my ASP.Net 3.5 web site from my old XP sp3 machine to a new Win 7 64-bit dev machine. The web application utilizes Master Pages, App_Themes with style sheets and images, as well as an image folder located off the main root. Additio ...

Puppeteer cannot fully render SVG charts

When using this code in Try Puppeteer: const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://www.barchart.com/futures/quotes/ESM19/interactive-chart/fullscreen'); const linkHandlers = await pa ...

The second pop-up modal fails to appear

I have successfully implemented 2 modal windows with the help of bootstrap. The first modal is used for adding a user to the database, and the second one is meant for editing an existing user. While the first modal works perfectly fine, the editing modal d ...