さて、私が書いたphpスクリプトにlocalStorageに保存したデータを渡す方法を見つけようとする際に問題が発生したので、それをサーバー上のデータベースに送信できます。以前にいくつかのコード ( https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest ) を見つけましたが、うまくいくように見えましたが、うまくいきませんでした。
データを保存し、それをphpscriptに渡そうとするコードは次のとおりです
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(initialize, showError, takeSnap);
}
else {
alert("Geolocation is not supported by this browser.");
}
}
function initialize(position) {
var lat = position.coords.latitude,
lon = position.coords.longitude;
var mapOptions = {
center: new google.maps.LatLng(lat, lon),
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true
}
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lon),
map: map,
title: "Current Location"
});
}
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 unkown error occurred.");
break;
}
}
function storeLocal(position) {
if (typeof (Storage) !== "undefined") {
var lat = position.coords.latitude,
lon = position.coords.longitude;
localStorage.latitude = lat;
localStorage.longitude = lon;
}
else {
alert("Your Browser doesn't support web storage");
}
return
}
function snapShot() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(storeLocal, showError);
}
else {
alert("Geolocation is not supported by this browser.");
}
var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.open("post", "snap.php?lat=" + localStorage.latitude + "&lon=" + localStorage.longitude, true);
oReq.send();
}
function reqListener() {
console.log(this.reponseText);
}
これは、データベースに値を保存するために私が書いたスクリプトです
<?php
// Connecting to the database
mysql_connect("localhost", "username", "password");
mysql_select_db("db_name");
$latitude = mysql_real_escape_string($_GET["lat"]);
$longitude = mysql_real_escape_string($_GET["lon"]);
// Submit query to insert new data
$sql = "INSERT INTO locationsTbl(locID, lat, lon ) VALUES( 'NULL', '". $latitude ."', '". $longitude . "')";
$result = mysql_query( $sql );
// Inform user
echo "<script>alert('Location saved.');</script>";
// Close connection
mysql_close();
?>