New to our community ?

Discover a world of possibilities! Join us and explore a vibrant community where ideas flourish and connections thrive.

One of Our Valued Members

Thank you for being part of our community. Your presence enriches our shared experiences. Let's continue this journey together!

Home php codes show active visitor on google map using php

show active visitor on google map using php

0

Welcome back to shortlearner.com, In our previous post we learn how to change password script is run in php.
Today we will learn how to get the user’s current location from the browser and show multiple locations mark on the map.
get visitor location using php
before starting this tutorial, first of all, we make a scenario to perform this task. we split this task into 4 parts.

in our first part, we create a database (‘demo‘) and a database table with the name of (location). in a database table (location) we have 3 entities (id),(latitude),(longitude).

in the second part we create a page index.php . in the index.php page, we put our javascript and Ajax code in the head section. the javascript code
helps us to fetch user’s location from the browser and the ajax code is helpful to store the location into our database table.
in the third part, we create a page getLocation.php which is a help to insert ajax data into the database
and in the final part we create a page showlocation.php. in the showlocation.php page, we fetch the users location from database and
shows on the google map with location mark.

index.php

<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Get Visitor Location using HTML5</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>

<script>

$(document).ready(function(){
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showLocation);
    } else { 
        $('#location').html('Geolocation is not supported by this browser.');
    }
});

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

	$.ajax({
		type:'POST',
		url:'getLocation.php',
		data:'latitude='+latitude+'&longitude='+longitude,
		success:function(msg){
            if(msg){
               $("#location").html(msg);
            }else{
                $("#location").html('Not Available');
            }
		}
	});

}
</script>
<style type="text/css">
	p{ border: 2px dashed #009755; width: auto; padding: 10px; font-size: 18px; border-radius: 5px; color: #FF7361;}
    span.label{ font-weight: bold; color: #000;}
</style>
</head>
<body>
    <p><span class="label">Your Geo-location:</span> <span id="location"></span></p>
</body>
</html>

getLocation.php

<?php
if(!empty($_POST['latitude']) && !empty($_POST['longitude'])){
    $con= mysqli_connect("localhost","root","root","demo");
    $qry="INSERT INTO `demo`.`location` (`latitude`, `longitude`) VALUES ('".$_POST['latitude']."', '".$_POST['longitude']."');";
    mysqli_query($con,$qry);
    //Send request and receive json data by latitude and longitude
    $url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.trim($_POST['latitude']).','.trim($_POST['longitude']).'&sensor=true';
    $json = @file_get_contents($url);
    $data = json_decode($json);
    $status = $data->status;
    if($status=="OK"){
        //Get address from json data
        $location = $data->results[0]->formatted_address;
    }else{
        $location =  '';
    }
    // dipslay address
    echo $location;
}
?>

showlocation.php

<!DOCTYPE html>
         <html>
         <head>
             <title></title>

         </head>
         <body>
       <script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyBUb3jDWJQ28vDJhuQZxkC0NXr_zycm8D0&callback=initMap" type="text/javascript"></script><script type="text/javascript">// <![CDATA[
 <?php 

        require('connection.php');
        $geq="SELECT * FROM location";
        $ger=mysqli_query($con,$geq);

        $e = "";
        while($rt=mysqli_fetch_array($ger))
        {
          $e[]= array("lat" => $rt['latitude'],"lng"=>$rt['longitude']);
         }
             ?>
var markers =<?php echo json_encode($e); ?>;
window.onload = function () {
var mapOptions = {
center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
var infoWindow = new google.maps.InfoWindow();
var lat_lng = new Array();
var latlngbounds = new google.maps.LatLngBounds();
for (i = 0; i < markers.length; i++) {
var data = markers[i]
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
lat_lng.push(myLatlng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: data.title
});
latlngbounds.extend(marker.position);
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
});
})(marker, data);
}
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds);

}

// ]]></script></pre>
<div id="dvMap" style="width: 500px; height: 500px;"></div>


         </body>
         </html>