Javascript-保存地理位置坐标

时间:2018-07-08 07:54:33

标签: javascript html local-storage

我怎样才能将坐标保存在本地存储中,这样它就不应每次都要求用户允许GPS或位置信息,以及一个按钮来清除本地存储值,以便它可以再次要求输入坐标?

仅供参考: 我正在使用Praytimes JS显示穆斯林的祈祷时间,但是对于每个位置,我都必须手动添加该位置的纬度和经度。

下面是我的代码:

<script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript"> 
  var x = document.getElementById("currentlocation");

  var geocoder;

  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
} 
//Get the latitude and the longitude;
function successFunction(position) {
    var lat = position.coords.latitude;
    var lng = position.coords.longitude;
    codeLatLng(lat, lng)
}

function errorFunction(){
    $('#currentlocation').html("Geocoder failed");
}

  function initialize() {
    geocoder = new google.maps.Geocoder();



  }

  function codeLatLng(lat, lng) {

    var latlng = new google.maps.LatLng(lat, lng);
    geocoder.geocode({'latLng': latlng}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
      console.log(results)
        if (results[1]) {
         //formatted address
         $('#currentlocation').html(results[0].formatted_address);
        //find country name
             for (var i=0; i<results[0].address_components.length; i++) {
            for (var b=0;b<results[0].address_components[i].types.length;b++) {

            //there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
                if (results[0].address_components[i].types[b] == "administrative_area_level_2") {
                    //this is the object you are looking for
                    city= results[0].address_components[i];
                    break;
                }
            }
        }
        //city data
        $('#currentlocation').html(city.short_name + " " + city.long_name)


        } else {
          $('#currentlocation').html("No results found");
        }
      } else {
        $('#currentlocation').html("Geocoder failed due to: " + status);
      }
    });
  }
</script>

<p id="currentlocation"></p>

<script type="text/javascript" src="http://praytimes.org/code/v2/js/PrayTimes.js"></script>    

<script type="text/javascript">
    function loadTable(position) {
        prayTimes.setMethod('MWL'); 
        var date = new Date(); // today
        var times = prayTimes.getTimes(date, [position.coords.latitude, position.coords.longitude]);
        var list = ['Fajr', 'Sunrise', 'Dhuhr', 'Asr', 'Maghrib', 'Isha', 'Midnight'];

        var html = '<table id="timetable">';
        html += '<tr><th colspan="2">'+ date.toLocaleDateString()+ '</th></tr>';
        for(var i in list)  {
            html += '<tr><td>'+ list[i]+ '</td>';
            html += '<td>'+ times[list[i].toLowerCase()]+ '</td></tr>';
        }
        html += '</table>';
        document.getElementById('table').innerHTML = html;
    }

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(loadTable);
    }
</script> 

2 个答案:

答案 0 :(得分:1)

使用坐标信息定义对象:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Http;
using System.IO;    // for StreamReader

namespace SendHttp
{
    class Program
    {
        static void Main(string[] args)
        {

            var request = (HttpWebRequest)WebRequest.Create("http://api.pushingbox.com/pushingbox?");

            var postData = "devid=";
            postData += "v12451BC5EA631A1";
            postData += "&message_parameter=";
            postData += "Test";
           // postData += "\r\n\r\n";
         var data = Encoding.ASCII.GetBytes(postData);

            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;

            using (var stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }

            var response = (HttpWebResponse)request.GetResponse();


            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
            Console.WriteLine(responseString);


        }

    }
}

将其保存在本地存储中:

var coordinatesObject = 
{
  lat: position.coords.latitude,
  lng: position.coords.longitude
}

获取:

localStorage.setItem('coordinates', 
JSON.stringify(coordinatesObject));

答案 1 :(得分:0)

var x = someType()
someType didSet { // change behavior of var }
x.behavior = newBehavior