I'm looking to store a user's latitude and longitude in my postgres database by utilizing the HTML5 map. What steps do I need to take to accomplish

After the user clicks to save their position, we will store it in our longitude and latitude columns. Thank you for helping us with this task!

Visit our Github repository here.

Below is the excerpt from our HTML file where users can save their location coordinates:

 <h1>Users#edit for <%= @user.id %></h1>
    <p>You can find me in app/views/users/edit.html.erb</p>
    <p><button onclick="geoFindMe()" data-id="<%= @user.id %>"id="finder-btn">Geo-Coordinate My Position</button>Send Coordinates to Database</p>
<div id="out"></div>
    <h2>Coordinates to DataBase!</br>lat, lon</h2>
    <a href="#" onclick="this.style.backgroundColor='#990000'">Paint it red</a>

Here is the JavaScript file used for handling the button click event:

$(function(){

  $('#finder-btn').on('click', function (){

    var currentUserId = $(this).attr('data-id')

    $.ajax({
      url: '/users/' + currentUserId,
      data: { latitude: LatLng[0], longitude: LatLng[1] },
      type: 'get',
      success: function(data) {
        console.log("Location successfully updated!")
      },
      error: function(err) {
        console.log("Error updating location")
      }
    });
  });
});


//update location for current_user

LatLng = [];
console.log(LatLng);

var latitude = LatLng[0]
var longitude = LatLng[1]



function geoFindMe() {
  var output = document.getElementById("out");

  if (!navigator.geolocation){
    output.innerHTML = "<p>Geolocation is not supported by your browser</p>";
    return;
  }

  function success(position) {
    var latitude  = position.coords.latitude;
    var longitude = position.coords.longitude;


    output.innerHTML = '<p>Latitude is ' + latitude + '° <br>Longitude is ' + longitude + '°</p>';

    var img = new Image();
    img.src = "https://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&zoom=13&size=300x300&sensor=false";

    // console.log(longitude);
    // console.log(latitude);
    //PLUCK into Location TABLE

    // latitude = lat_Jon;
    // longitude = lon_Jon;

    LatLng.push(latitude);
    LatLng.push(longitude);


    output.appendChild(img);
  };

  function error() {
    output.innerHTML = "Unable to retrieve your location";
  };

  output.innerHTML = "<p>Locating…</p>";

  navigator.geolocation.getCurrentPosition(success, error);
}

We also need to update the location details in our users_controller for latitude and longitude:

def update
    # @user = User.find(session[:user_id])
    user_id = current_user.id
    @user = User.find(user_id)
    @user.update_attributes(user_params)

    puts @user.latitude
  end

Answer №1

There are a few issues at play here that may be causing some confusion.

  1. The problem lies in the fact that you are using a GET request instead of a POST or PUT when attempting to update the user's latitude and longitude.

    To resolve this, modify your AJAX call from type: 'get' to type: 'post'. This change will help Rails route your request to the correct controller action (users_controller#update).

  2. Within your users_controller, make sure to use params[:id] to locate the user. The code should resemble:

    user = User.find(params[:user_id])

  3. Similarly, after locating the user, extract the latitude and longitude values from the params. Your user_params method assumes certain parameters which are not strictly enforced. It appears as though it expects data in this format:

    { 'user': { 'longitude': '29.388', 'latitude': '187.39848' } }

    whereas your actual params look like:

    { 'longitude': '29.388', 'latitude': '182.3888' }

    To address this issue, gather the latitude and longitude using params[:longitude] and params[:latitude]

    A possible implementation would be:

    class UsersController < ApplicationController
      def update
        user = User.find(params[:id])
        user.update!(latitude: params[:latitude], longitude: params[:longitude])
      end
    end
    

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

JavaScript is failing to display array elements

I'm currently in the process of developing a filtering system for a festival website. The price filter is up and running smoothly, but now I'm facing a challenge with the genre filter. For the genre filter, I've created an array named filte ...

Using Javascript to take a screenshot of the HTML page and save it

Can you capture the displayed HTML page using JavaScript? I am interested in generating a "minimap" of an HTML page to allow for easy navigation. ...

Can Google Maps markers be transformed into checkboxes for use?

Is there a way to use Google Maps as a multiple locations picker, where users can select map markers and submit them through a form? ...

I am looking to create a route with parameters in Next.js, as well as without any parameters

I am working on a NEXTJS project and utilizing SSR for data fetching. However, I am trying to implement the following scenario: When users land on the "/" route, they should be presented with a random product detail page. But if they search for a specific ...

What occurs when socket.io events are not properly handled?

Is socket.io ignoring or dropping messages? I am asking this because there is a client with multiple states, each having its own set of socket handlers. The server notifies the client of a state change and then sends messages specific to that state. Howeve ...

I'm trying to use Route.get() but it seems I forgot to include a callback function. What mistake did I make?

I've searched through various answers on different platforms, but I'm still struggling to understand. What mistake have I made? Can someone provide assistance? *revised. I have included requiring routes and app.use. It seems like the function is ...

Loading game resources in advance for future or immediate utilization

I'm currently developing a game UI that involves a large number of image files, totaling around 30MB in size. I've been caching these images to the disk using service workers, but some of them are quite large at 3MB each. Even when they are retri ...

Discover distinct and recurring elements

Having two sets of JSON data: vm.userListData = [{ "listId": 1, "permission": "READ" }, { "listId": 2, "permission": "WRITE" }, { "listId": 2, "permission": "READ" }, { "listId": 3, ...

What is the correct way to invoke a function from an external JavaScript file using TypeScript?

We are currently experimenting with incorporating Typescript and Webpack into our existing AngularJS project. While I have managed to generate the webpack bundle, we are facing an issue at runtime where the program is unable to locate certain functions in ...

What is the best way to send a file and retrieve a value on Internet Explorer versions 8 and 9?

Greetings everyone, I am encountering a technical issue that has consumed a significant amount of my time. I am hopeful that you may be able to assist me with resolving it. In my table, I have a list of files along with corresponding document types and de ...

Trigger an event in Javascript/ASP.net following a dropdownlist selection

On a single HTML page, I have incorporated three dropdown lists for country, city, and district with an initial blank selected value, along with a Google map. The aim is to automatically center and zoom in on the map whenever users make selections from the ...

Is there a way to apply a scaling transformation to an element in react native that is relative to the window size by a percentage?

One method that can be used to achieve a similar result is by following this formula: const { width } = useWindowDimension(); const percentage = width * 0.8; // 80% of the window <ComponentOrElement style={ width: percentage } /> However, this calc ...

Storing JSON data into a file

I am trying to save a JSON object to a file using a PHP script that is triggered by an AJAX POST request. The data and filename are provided in the POST request. var results = $('results'); var filename = $('#filename').val(); $.ajax( ...

Switch out the selection inputs for interactive images that can be clicked on

My code below enhances the user experience by converting an HTML selection into a more visually appealing image clickable version. Clicking on an image selects the corresponding value in a hidden selection field within the DOM. I require assistance in mod ...

Passing an array list back to the parent component in ag-grid(Vue) - A step-by-step guide

Currently, I am integrating AG Grid with Vue. My project has a specific requirement where two checkboxes are displayed using a cellRendererFramework. However, I am facing difficulties in fetching the values of these checkboxes from the row definitions. The ...

Angular 4: Harnessing the Power of Pipe Chaining

While using the *ngFor directive, I am attempting to apply multiple pipes but I'm encountering difficulties getting it to function properly. <tr *ngFor="let order of orders | filter:filter; let i=index | paginate: {itemsPerPage:7 , currentPage:p}" ...

Access navigation through Google Maps on an Android device directly from the website

Currently, I am in the process of developing an angular 4 website that fetches a list of latitude and longitude coordinates from the server. One of the key features on this website is a button that takes the user to Google Maps, where a route is constructe ...

What is the best way to design an angular directive or service specifically for straightforward pagination featuring only next and previous options?

Within a block of div tags, an ng-repeat directive is being used to display sets of 3 divs at a time. By clicking on the next button, the next set of 3 divs should be displayed, and the same goes for the previous button. Check out the HTML code below: &l ...

Having trouble passing arguments to button methods in jasmine when applying vue and moment libraries

I am working on unit testing a Vue app using `jasmine` and `karma`. Here is an example of the code inside one of my components: After fetching data from a database with `v-for=(data,index)`, I am displaying the `data.date` in the template: <p class=&qu ...

Dealing with hidden elements poses a challenge for Selenium as it struggles to catch ElementNotVisibleException

Currently, I am working on creating user interface tests using selenium and I came across a method that is supposed to handle non-existing elements and hidden elements. The issue arises in the second catch block where the method consistently returns &apos ...