The loading of Google maps occurs simultaneously with ongoing AJAX requests

I am currently working with the Google Maps API in combination with rails 5.0.4.

My goal is to have the map center on the user's location and populate the latitude and longitude fields with the corresponding coordinates. Right now, the lat, lng fields are filled correctly, but the map loads before the asynchronous calls are completed, causing a mismatch between the map position and the coordinates. This issue resolves itself after a refresh, but it remains a problem upon initial load. I attempted to use a promise to address this, but was unsuccessful.

What would be the most effective approach to solving this?

$(document).ready(function(){

      function getUserCoordinates() {
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(setCoords);
        };
      };

      function setCoords(position) {
        lat = position.coords.latitude;
        lng = position.coords.longitude;
        updateUserLat(lat);
        updateUserLng(lng);
        document.getElementById("latitude").value = lat.toFixed(6);
        document.getElementById("longitude").value = lng.toFixed(6);
      };

      function updateUserLat(lat) {
        $.ajax({
          type: 'PATCH',
          url: '/users/:id',
          data: {'user[latitude]': lat}
        });
      };
      function updateUserLng(lng) {
        $.ajax({
          type: 'PATCH',
          url: '/users/:id',
          data: {'user[longitude]': lng}
        });
      };

      getUserCoordinates();

      function initMap(){
          initialize();
      };

});

Answer №1

Instead of keeping the initMap() function within the document ready wrapper, move it outside so you can call it directly once your lat/long values are set.

Placing it inside the document ready wrapper will cause the map to initialize when the page loads, which is not ideal.

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

Upon attempting to retrieve a package version, NPM responds with an error stating "bash command not found."

I recently set up my project with a package.json file that includes the nodemon package among others. When I run #npm list --depth 0 in the terminal, this is what I see: ├─┬ [email protected] However, when I try to check the version of nodemo ...

Dynamically Inject HTML with Drag-and-Drop Interaction

Looking for an easy method to move html elements or content around on a webpage? The objective is to drag the element and release it onto a designated area. After dropping the element, customized html content will be added dynamically depending on ...

The surprising behavior of Rails rendering partials even when they are commented out has

I'm intrigued by how Rails 5 handles partials and if there might be a hidden problem I haven't encountered yet. On my current page, I have two partials - one that is included in the HTML itself, and another that is supposed to render inside an aj ...

Having trouble with JQuery click function not executing on initial click?

As I scoured through various resources looking for solutions to issues similar to mine, I stumbled upon numerous helpful insights. However, after going through approximately 15 of them, I hit a roadblock in finding someone who has encountered the exact sam ...

<div><!-- including: unknown --></div>

Need some assistance with this issue. The ng-include path I am using is "http://localhost:8080/coffeeprojects/calc.html". I tested the path and it seems to be working. However, despite organizing the files and improving the path as suggested in some resp ...

What is the best way to attach two separate event listeners to a single button?

I'm attempting to have one button trigger two different functions, but I haven't been successful so far. I tried adding the second event listener as indicated by the // part, but it didn't work. The two functions should be executed sequentia ...

Executing a long job in PHP (Laravel) while simultaneously making an AJAX call

Looking to create a real-time progressing bar? I attempted to incorporate this example into my Laravel project but seem to have missed a step. Here is my HTML and JavaScript code: <div style="border:1px solid black;width:500px;height:80px"> &l ...

Searching for items in one array within another using Lodash

Hey there! Currently utilizing the lodash library. I'm looking to check if the phone number in receivedMessagesMock matches any of the phone numbers in contactsMocks. If receivedMessagesMock.phone matches contactsMocks.phoneNumbers.value, I want to ...

What is the best way to hear an event emitted by a component?

I am trying to listen for an event in Chrome DevTools Vue, but I'm not sure how to target it. For a Root event, I typically use: this.$root.$on("note_id", (note_id) => (this.note_id = note_id)); But how do I address an event that origina ...

Encountering a 404 error in Codeigniter when making an AJAX call

After successfully implementing an upload form with ajax, I encountered some issues when attempting to delete uploaded photos. Initially, I received a "csrf protection error," which led me to disable csrf protection, only to then encounter a "404 not found ...

When encountering error code EINTEGRITY during npm installation, a warning about a potentially corrupted tarball may be displayed

I have been facing an issue for the last three days with my react+vite project on Windows 10. Whenever I attempt to install dependencies using npm install, I encounter the following error: npm WARN tarball tarball data for fast-levenshtein@https://registry ...

Concealing a column in ngx-datatable Ionic

I am just starting to work with NGX-datatable and I need to populate my data table in my Ionic app with data from Firebase. Here is the format of the JSON returned from Firebase: If I choose not to use the User_id as a column, how can I access the User_id ...

What is the process for implementing pagination in vue-tables-2 with a Laravel REST API?

I'm looking to implement pagination on Vue server-table using a Laravel endpoint. How can I achieve this? Below is my component setup: <template> <div> <v-server-table :columns="columns" url="/object/find" :options="option ...

Establish the condition if the array is present

I am looking to conditionally set a state based on the existence of data retrieved from the server. const [names, setNames] = useState([...details?.names]) The details object is passed in as props and fetched from the database. The array details.names com ...

Issue with displaying value after rendering

After fetching pool data from the constants file, my task was to create a featured vault - the one with the highest APY Reward value obtained from the API. Even though I successfully fetched all three values and performed the calculations, I am facing an i ...

Utilize Angular2's input type number without the option for decimal values

Is there a way to prevent decimals from being entered in number inputs for Angular 2? Instead of using patterns or constraints that only invalidate the field but still allow typing, what is the proper approach? Would manually checking keystrokes with the ...

Using Laravel to set cookies with Ajax

I am facing difficulties in setting cookies through laravel using ajax. Despite reading several questions and posts, I have not been able to find a solution. My issue involves a dropdown that triggers a javascript function to send its value to a controlle ...

Uploading files using Ajax without the need for additional plugins or submitting a form

I have been struggling to find a solution for uploading files via Ajax when the input field is not enclosed within a form tag. I have already attempted this method. This is the HTML snippet: <span id="user-image-up-btn">Upload Image</span> &l ...

Adjust the FlipClock time based on the attribute value

When setting up multiple FlipClock objects on a page, I need to retrieve an attribute from the HTML element. The specific HTML tag for the clock is: <span class="expire-clock" data-expire="2015-09-22"> Is there a way to access '2015-09-22&apos ...

modify the class's CSS style

Hey there! I'm having an issue with my code snippet. My goal is to change the background color of both fields with the class 'navicon', as shown in the function fu(). However, it's not working as expected. Changing the color based on id ...