创建一个Javascript对象来容纳用户'的地理位置坐标

Creating a Javascript object to hold user's geolocation co-ordinates

本文关键字:用户 坐标 地理位置 一个 对象 Javascript 创建      更新时间:2023-09-26

我想创建一个Javascript对象,让我们将其命名为"geoloc",并将其放置在我创建的Javascript库中。

此对象将使用html5地理位置API将用户位置的position.coords.latitudeposition.coords.longitude值存储到两个对象属性中,让我们将它们命名为geoloc.latitudegeoloc.longitude

然后我可以在我的html代码中使用它们,如下所示:

<script type="text/javascript"> 
    document.writeln('Your latitude is: ', geoloc.latitude);
    document.writeln('Your longitude is: ', geoloc.longitude); 
</script> 

我已经试过了:

<a href="http://html5doctor.com/finding-your-position-with-geolocation">this</a> 

但是它显示一个警报;我需要将对象变量返回到我的html代码中。

提前感谢

你的意思是简单地创建一个JS对象来存储你的信息吗?

function geoloc(latitude, longitude)
{
    this.latitude=latitude;
    this.longitude=longitude;
}

然后像这样实例化:

var userLocation = new geoloc(lat, lon);

这向你展示了如何使用谷歌API 获取lat和long

http://www.merkwelt.com/people/stan/geo_js/sample.html

您只需要更改displayPosition函数中的代码。不要向用户发出警报,而是将值存储在变量中,并在任何需要的地方使用它们。

mycode = {
     lat: null,
     lon: null
};
function displayPosition(position) {
     mycode.lat = position.coords.latitude;
     mycode.lon = position.coords.longitude;
}