【问题标题】:PHP - To get current Map Location and insert details into database using ajax and phpPHP - 使用 ajax 和 php 获取当前地图位置并将详细信息插入数据库
【发布时间】:2016-10-26 16:47:26
【问题描述】:

这可以帮助您获取当前位置,将其显示在浏览器上,并使用 php、javascript 和 ajax 将其保存到数据库中。

HTML 页面 - index.html

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script type = "text/javascript">
        var getLocLatitude = "";
        var getLocLongitude = "";
        var locDetails = new Array();
        var img = new Image();

        $(document).ready(geoFindMyLocation);

        function geoFindMyLocation() {

            var output = document.getElementById("maplocation");

            if (!navigator.geolocation) {
                locDetails.push("Geolocation is not supported by your browser");
                return;
            }

            function success(position) {

                var latitude = position.coords.latitude;
                var longitude = position.coords.longitude;
                getLocLatitude = latitude;
                getLocLongitude = longitude;

                var latlng = latitude + "," + longitude;
                var url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + latlng + "&sensor=false";

                img.src = "http://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&zoom=13&size=300x300&sensor=false&key=AIzaSyBJ3vEue3yTVxWjo7i3QZiQBH0Eg2m7E4M";
                output.appendChild(img);
                getLocationDetailFromGeoLocation(url);
            };

            function error() {
                locDetails.push("Unable to retrieve your location");
            };

            navigator.geolocation.getCurrentPosition(success, error);

            $('#save_to_db').click(function() {
                var street = $('#street').html();
                var area = $('#area').html();  
                var city = $('#city').html();
                var state = $('#state').html();
                var country = $('#country').html();
                $.ajax({
                    url: 'saveit.php',
                    type: 'POST',
                    data: {
                        street: street, area: area, city: city, state: state, country: country
                    }
                });
             });

        }

        function getLocationDetailFromGeoLocation(url) {

            $.getJSON(url, function (data) {

                for (var i = 0; i < data.results.length; i++) {
                    var address = data.results[i].formatted_address;
                    locDetails.push(address);

                    document.getElementById("street").innerHTML = locDetails[0];
                    document.getElementById("area").innerHTML = locDetails[1];
                    document.getElementById("city").innerHTML = locDetails[2];
                    document.getElementById("state").innerHTML = locDetails[3];
                    document.getElementById("country").innerHTML = locDetails[4];
                }   

            });
        }


    </script>
</head>
<body>
    <div id="maplocation"></div>
    <br>
    DETAILS:
    <div id="street"></div>
    <div id="area"></div>
    <div id="city"></div>
    <div id="state"></div>
    <div id="country"></div>
    <br>
    <button id="save_to_db">Save To DB</button>
</body>

PHP 页面 - saveit.php

<?php
$street = $_POST['street']; //get posted data    
$area = $_POST['area'];
$city = $_POST['city'];
$state = $_POST['state']; 
$country = $_POST['country']; 

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mapdb";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $conn->prepare ("INSERT INTO maptable (street, area, city, state, country) VALUES (:street, :area, :city, :state, :country)");
    $stmt -> bindParam(':street', $street);
    $stmt -> bindParam(':area', $area);
    $stmt -> bindParam(':city', $city);
    $stmt -> bindParam(':state', $state);
    $stmt -> bindParam(':country', $country);
    $stmt -> execute();

    echo "Map Details inserted successfully";
    }
catch(PDOException $e)
    {
    echo $stmt . "<br>" . $e->getMessage();
    }
   $conn = null;
?>

SQL 数据库表

CREATE TABLE `maptable` (
`id` int(11) NOT NULL,
`street` varchar(100) NOT NULL,
`area` varchar(50) NOT NULL,
`city` varchar(50) NOT NULL,
`state` varchar(50) NOT NULL,
`country` varchar(50) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1; 

这是一个完整的解决方案 - 运行良好

【问题讨论】:

  • 有什么问题?另外作为旁注,您应该真正验证/清理来自前端的任何内容,尤其是当它进入数据库时​​。
  • 是的,你是对的。谢谢,但只是一个解决方案。任何需要它的人都可以对其进行验证/消毒或修改以适应口味。

标签: php jquery html ajax pdo


【解决方案1】:

由于 PHP 是一种服务器端语言,您必须使用 Javascript 或更好的 JQuery。

工作DEMO

$(document).ready(function(){
            //Chek if API is aviable
            if (navigator.geolocation) {
                //Get coords
                navigator.geolocation.getCurrentPosition(function(position) {
                    //alert for demo
                    alert("Lat: " + position.coords.latitude + " / Long: " + position.coords.longitude)
                    //Store your coords....
                }, showError); //Geolocation error
            }

            function showError(error) {
                switch (error.code) {
                    case error.PERMISSION_DENIED:
                        alert("User denied the request for Geolocation.");
                        break;
                    case error.POSITION_UNAVAILABLE:
                        alert("Location information is unavailable.");
                        break;
                    case error.TIMEOUT:
                        alert("The request to get user location timed out.");
                        break;
                    case error.UNKNOWN_ERROR:
                        alert("An unknown error occurred.");
                        break;
                }
            }
        });

【讨论】:

  • 这个解决方案如何将其保存到数据库中?
  • 要保存这些东西,您必须对 php 页面进行 ajax 调用,将变量带入 GET 或 POST,然后在 php 页面中保存它们。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-16
  • 1970-01-01
  • 2021-06-11
  • 2012-11-30
  • 1970-01-01
  • 1970-01-01
  • 2012-07-14
相关资源
最近更新 更多