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();
};
});