我尝试在第一次运行时在 cookie 中设置 getcurrentLocation。 但没能做到。
我当前的cookie.js
export default{
/**
* @func persistent
*
* @returns {boolean} Returns true if cookies are persistent, false if not.
*/
persistent() {
if (navigator.cookieEnabled != null && navigator.cookieEnabled) {
const cookieName = "dummy.cookie.data";
const expires = new Date();
expires.setYear(expires.getYear() + 1930); // We try to save a cookie for 30 years
document.cookie = `${cookieName}; expires=${expires.toUTCString()}`;
if (document.cookie.indexOf(cookieName) !== -1) {
this.remove(cookieName);
return true;
}
const userMarket = getLocation();
document.cookie = `${cookieName}; expires=${userMarket}`;
function getLocation() {
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(geoSuccess, geoError);
} else {
console.log("Geolocation is not supported by this browser.");
}
}
function geoSuccess(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
console.log("lat:" + lat + " lng:" + lng);
}
this.remove(cookieName);
}
return false;
}
};
我想添加 navigator.geolocation.getCurrentPosition 来获取其值。
//示例
navigator.geolocation.getCurrentPosition(
(position) => {
this.setState({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
error: null,
});
},
(error) => this.setState({ error: error.message }),
{ enableHighAccuracy: false, timeout: 20000, maximumAge: 1000 },
);
这里我如何能够创建一个util函数来获取地理位置?
任何线索都会有帮助。 谢谢
最佳答案
在您的示例中,您尝试使用空名称设置 cookie,并且此 cookie 是使用空名称和 dummy.cookie.data
值设置的。
您还需要设置值。
示例:
document.cookie = `${cookieName}=yourExampleValue; expires=${expires.toUTCString()}`;
这是docs .
关于javascript - Reactjs : How to set navigator. geolocation.getCurrentPosition 在cookie中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56148584/