Matodobra24
Matodobra24

Reputation: 55

Load current geolocation into a database with PHP

I'm currently trying to make an application that uploads the users current location into my mysql database. I know how to use google maps in javascript. I know enough to make php work.

What I don't know is how can I take my current location and continually loop it through my database. I was hoping to update the users location every 2 minutes without Post & Get variables. If anybody has any information, any documentation or anything that would be great. I tried looking it up.

I found people saying to use AJAX but I'm not sure how that would loop through my current location without some kind of interaction.

I also saw the other talking about turning it into JSON data.

Any thoughts would be greatly appreciated!

Upvotes: 1

Views: 1801

Answers (1)

Vaviloff
Vaviloff

Reputation: 16856

I'll answer with simplified concept code for you to get the general idea.

First you need to add the location polling functionality in your web application with Javascript:

// We only start location update process if browser supports it
if ("geolocation" in navigator) 
{
    request_location();
} 

// Requesting location from user
function request_location()
{
    // Will repeat the process in two minutes
    setTimeout(request_location, 1000*60*2);

    // Get location info from browser and pass it to updating function
    navigator.geolocation.getCurrentPosition(update_location);
}

// Sending location to server via POST request
function update_location(position)
{
    // For simplicity of example we'll 
    // send POST AJAX request with jQuery
    $.post("/update-location.php",
    {
        latitude : position.coords.latitude,
        longtitude : position.coords.longitude
    },
    function(){
        // Position sent, may update the map
    });
}

Then on the server side you must receive the coordinates from the above AJAX request:

<?php 

    $latitude = filter_input(INPUT_POST, 'latitude', FILTER_VALIDATE_FLOAT);
    $longtitude = filter_input(INPUT_POST, 'longtitude', FILTER_VALIDATE_FLOAT);

    if($latitude && $longtitude)
    {
        // @TODO: Update database with this data.
    }

Upvotes: 1

Related Questions