我发现这个很棒的脚本可以根据经度和纬度找到用户的邮政编码。通过阅读代码,我发现必须有一个状态ID才能使信息变得可见。我的问题是,是否可以将信息的cookie放入状态ID中。所以它会根据这个人放一个邮政编码,我想制作一个该邮政编码的cookie,以便在我的网站上进一步使用它。它使用地理定位并将信息插入谷歌并获取邮政编码。所以我想抓住那个邮政编码并尽可能地创建一个cookie。任何帮助将不胜感激。感谢。
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<p> </p>
<center>
<p id="status"></p>
<script>
$(function(){
var GETZIP = {
getLocation: function(){
$('#status').text('Searching...');
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(GETZIP.getZipCode, GETZIP.error, {timeout: 7000});//cache it for 10 minutes
}else{
GETZIP.error('Geo location not supported');
}
},
index: 0,
error: function(msg) {
if(msg.code){
//this is a geolocation error
switch(msg.code){
case 1:
$("#status").text('Permission Denied').fadeOut().fadeIn();
break;
case 2:
$("#status").text('Position Unavailable').fadeOut().fadeIn();
break;
case 3:
GETZIP.index++;
$("#status").text('Timeout... Trying again (' + GETZIP.index + ')').fadeOut().fadeIn();
navigator.geolocation.getCurrentPosition(GETZIP.getZipCode, GETZIP.error, {timeout: 7000});
break;
default:
//nothing
}
}else{
//this is a text error
$('#error').text(msg).addClass('failed');
}
},
getZipCode: function(position){
var position = position.coords.latitude + "," + position.coords.longitude;
$.getJSON('proxy.php',{
path : "http://maps.google.com/maps/api/geocode/json?latlng="+position+"&sensor=false",
type: "application/json"
}, function(json){
//Find the zip code of the first result
if(!(json.status == "OK")){
GETZIP.error('Zip Code not Found');
return;
}
var found = false;
$(json.results[0].address_components).each(function(i, el){
if($.inArray("postal_code", el.types) > -1){
$("#status").text(Your zip code: + el.short_name);
found = true;
return;
}
});
if(!found){
GETZIP.error('Zip Code not Found');
}
});
}
}
GETZIP.getLocation();
});
</script>
答案 0 :(得分:0)
假设您的代码正确检索el.short_name
中的邮政编码,您可以在检索后立即存储该值:
这是一个创建cookie的功能:
function createCookie(name,value,days) {
var expires = "", date;
if (days) {
date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
expires = "; expires=" + date.toGMTString();
}
document.cookie = name+"="+value+expires+"; path=/";
}
以下是getZipCode的修改版本,它在检索邮政编码后立即写入cookie:
getZipCode: function(position){
var position = position.coords.latitude + "," + position.coords.longitude;
$.getJSON('proxy.php',{
path : "http://maps.google.com/maps/api/geocode/json?latlng="+position+"&sensor=false",
type: "application/json"
}, function(json){
//Find the zip code of the first result
if(!(json.status == "OK")){
GETZIP.error('Zip Code not Found');
return;
}
var found = false;
$(json.results[0].address_components).each(function(i, el){
if($.inArray("postal_code", el.types) > -1){
$("#status").text(Your zip code: + el.short_name);
createCookie("zipcode", el.short_name, 365);
found = true;
return;
}
});
if(!found){
GETZIP.error('Zip Code not Found');
}
});
}