如何使用JavaScript在Cord SQL中存储当前的地理位置 - Cordova

时间:2017-12-15 06:51:42

标签: cordova

我尝试使用Geolocationsq-lite websql存储在Google Chrome浏览器存储空间中...



var db;

window.onload = function() {
  document.getElementById('btnSave').addEventListener('click', saveData);
  db = window.openDatabase("geolocation", "1.0", "Technorigins", 200000);
}

function saveData(e) {
  db.transaction(saveRecord, onSuccessdb, onErrordb);
}

function saveRecord(transaction) {
  var latitude = document.getElementById('latitude').value;
  var longitude = document.getElementById('longitude').value;
  transaction.executeSql('CREATE TABLE IF NOT EXISTS geol_cordova (id INTEGER PRIMARY KEY AUTOINCREMENT, latitude TEXT NOT NULL, longitude TEXT NOT NULL) ');
  var sql = "INSERT INTO geol_cordova (latitude,longitude) VALUES ('" + latitude + "', '" + longitude + "')";

  transaction.executeSql(sql);
  transaction.executeSql("SELECT * FROM geol_cordova", [], onSuccessdb, onErrordb);
  alert(sql);
}

function getSuccess(transaction, result) {
  var rows = result.rows;
  for (var x = 0; x < rows.length; x++) {
    var latitude = result.rows[x].Latitude;
    var longitude = result.rows[x].Longitude;
    var out = "<li>" + latitude + "<br/>" + longitude + "</li>";
    document.getElementById('geolo').innerHTML += out;
  }

  $('#geolo').listview('refresh');
}

function getError(e) {
  alert(e);
}

function onSuccessdb() {
  alert("Location Saved");
}

function onErrordb(error) {
  alert("SQL error: ");
}

document.addEventListener("deviceready", onDeviceReady, false);

var watchID = null;

function onDeviceReady() {

  var options = {
    timeout: 30000,
    maximumAge: 60000
  };
  watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);
}

function onSuccess(position) {
  var element = document.getElementById('geolocation');
  element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' +
    'Longitude: ' + position.coords.longitude + '<br />' +
    'GPS Position: ' + distance('23.054996', '72.595171', position.coords.latitude, position.coords.longitude, 'ME') + ' Metres' +
    '<hr />' + element.innerHTML;
  document.getElementById('latitude').value = position.coords.latitude;
  document.getElementById('longitude').value = position.coords.longitude;
}

function onError(error) {
  alert('code: ' + error.code + '\n' +
    'message: ' + error.message + '\n');
}

function distance(lat1, lon1, lat2, lon2, unit) {
  var radlat1 = Math.PI * lat1 / 180
  var radlat2 = Math.PI * lat2 / 180
  var theta = lon1 - lon2
  var radtheta = Math.PI * theta / 180
  var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
  dist = Math.acos(dist)
  dist = dist * 180 / Math.PI
  dist = dist * 60 * 1.1515
  if (unit == "K") {
    dist = dist * 1.609344
  }
  if (unit == "N") {
    dist = dist * 0.8684
  }
  if (unit == "ME") {
    dist = dist * 1.609344 * 1000
  }
  return dist
}
&#13;
<!DOCTYPE html>
<html>

<head>
  <meta name="format-detection" content="telephone=no">
  <meta name="msapplication-tap-highlight" content="no">
  <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
  <link rel="stylesheet" type="text/css" href="css/index.css">
  <title>geolocation watchPosition</title>
  <link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
  <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
  <script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
</head>

<body>
  <div data-role="page">
    <div data-role="header">
      <h1>Database Storage</h1>
    </div>
    <div data-role="main" class="ui-content">
      <p id="geolocation">Watching geolocation...</p>
      <input type="hidden" id="latitude" value="" />
      <input type="hidden" id="longitude" value="" />
      <button id="btnSave" type="submit">Save</button>
      <ul id="geolo" data-role="listview">
      </ul>
    </div>
  </div>
  <script type="text/javascript" src="cordova.js"></script>
  <script type="text/javascript" src="js/index.js"></script>
  <link rel="stylesheet" type="text/css" href="css/overrides.css" />
</body>

</html>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:0)

对于Web SQL数据库,如果数据库结构不存在,我们需要创建它。如果不存在,openDatabase幸运地自动创建数据库,同样,我们使用SQL短语“if not exists”来确保新的checkins表如果已经存在则不会被覆盖。我们必须预先定义数据的结构,即checkins表中每列的名称和类型。每行代表一次签到。

  $percentage = round( ( ( $product->get_regular_price() - $product->get_sale_price() ) / $product->get_regular_price() ) * 100 );

this.db = openDatabase('geomood', '1.0', 'Geo-Mood Checkins', 8192);
this.db.transaction(function(tx) {
  tx.executeSql("create table if not exists " +
    "checkins(id integer primary key asc, time integer, latitude float," +
              "longitude float, mood string)",
    [],
    function() { console.log("siucc"); }
  );
});

答案 1 :(得分:0)

			var db;
            
        window.onload=function()
        {
            document.getElementById('btnSave').addEventListener('click', saveData);
            db = window.openDatabase("geolocation",  "1.0", "Technorigins", 200000);
			
        }
        
        function saveData(e)
        {
           
            
           
            db.transaction(saveRecord, onSuccessdb, onErrordb);
			
        }
            
        function saveRecord(transaction)
        {
            var latitude= document.getElementById('latitude').value;
            var longitude= document.getElementById('longitude').value;
		
            transaction.executeSql('CREATE TABLE IF NOT EXISTS geol_cordova (id INTEGER PRIMARY KEY AUTOINCREMENT, latitude TEXT NOT NULL, longitude TEXT NOT NULL) ');
            
            var sql= "INSERT INTO geol_cordova (latitude,longitude) VALUES ('" + latitude +"', '" + longitude + "')";
           transaction.executeSql(sql); 
		   alert(sql);
		   transaction.executeSql("SELECT * FROM geol_cordova", [], getSuccess, getError);
        }
		
		 function getSuccess(tx, result)
        {
            var rows = result.rows;
            for(var x=0; x< rows.length; x++){
                var latitude = result.rows[x].latitude;
                var longitude = result.rows[x].longitude;
                var out = "<li>" + latitude + "<br/>" + longitude + "</li>";
                document.getElementById('geolo').innerHTML += out;
            }
            
            $('#geolo').listview('refresh');
        }
            
        function onSuccessdb()
        {
            alert("Location Saved");
        }
            
        function onErrordb(error)
        {
            alert("SQL error: ");
        }
		//-----------------
		function getError(e)
        {
            alert(e);
        }
            
        
		
		
			// Wait for device API libraries to load
				//
				document.addEventListener("deviceready", onDeviceReady, false);

				var watchID = null;

				// device APIs are available
				//
				function onDeviceReady() {
					// Throw an error if no update is received every 30 seconds
					var options = { timeout: 30000 , maximumAge : 60000};
					watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);
				}

				// onSuccess Geolocation
				//
				function onSuccess(position) {
					var element = document.getElementById('geolocation');
					element.innerHTML = 'Latitude: '  + position.coords.latitude      + '<br />' +
										'Longitude: ' + position.coords.longitude     + '<br />' +
										'GPS Position: ' + distance('23.054996', '72.595171', position.coords.latitude, position.coords.longitude, 'ME') + ' Metres'  +
										'<hr />'      + element.innerHTML;
										document.getElementById('latitude').value=position.coords.latitude;
										document.getElementById('longitude').value=position.coords.longitude;
				}

				// onError Callback receives a PositionError object
				//
				function onError(error) {
					alert('code: '    + error.code    + '\n' +
						  'message: ' + error.message + '\n');
				}
				
				function distance(lat1, lon1, lat2, lon2, unit) {
				var radlat1 = Math.PI * lat1/180
				var radlat2 = Math.PI * lat2/180
				var theta = lon1-lon2
				var radtheta = Math.PI * theta/180
				var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
				dist = Math.acos(dist)
				dist = dist * 180/Math.PI
				dist = dist * 60 * 1.1515
				if (unit=="K") { dist = dist * 1.609344 }
				if (unit=="N") { dist = dist * 0.8684 }
				if (unit=="ME") { dist = dist * 1.609344 * 1000}
				return dist
				}
<div data-role="page">
        <div data-role="header"><h1>Database Storage</h1></div>
        <div data-role="main" class="ui-content">
		<p id="geolocation">Watching geolocation...</p>
		<input type="hidden" id="latitude" value="" />
		<input type="hidden" id="longitude" value="" />
		<button id="btnSave" type="submit">Save</button>
		<ul id="geolo" data-role="listview">
        </ul>
		<script type="text/javascript" src="cordova.js"></script>
        <script type="text/javascript" src="js/index.js"></script>
		<link rel="stylesheet" type="text/css" href="css/overrides.css" />
		</div><!-- main-->
        </div><!-- page -->

答案 2 :(得分:0)

查看https://github.com/localForage/localForage

它允许使用WebSQL或IndexedDB保存结构化信息,无论WebView可以访问什么。