返回首页 Apache Cordova 教程

使用本地API

在本部分中,我增加了给员工添加他/她的位置信息标签的能力。在本示例应用程序中,我们在一个警告中显示原始信息(经度/纬度)。在现实生活中的应用程序中,我们通常在数据库中保存位置信息作为员工信息的一部分,并在一张图上显示。

当将应用程序作为一个Cordova 应用程序在你的设备上运行时,下面的这些代码就会工作。当页面是由http:// 协议服务时,这些代码也会在桌面系统中的Chrome上工作,并且在Firefox中,忽视该协议(http:// 或 file://)。

步骤

1、增加geolocaton插件到你的项目中:

cordova plugin add org.apache.cordova.geolocation

2、在index.html中,增加以下列表项到employee-tpl模板:

<li class="table-view-cell media">
  <a hre="#" class="push-right add-location-btn">
      <span class="media-object pull-left"></span>
      <div class="media-body">
          Add location
      </div>
  </a>
</li>

3、在EmployeeView的initialize()函数中,为Add Location列表项的单击事件注册一个事件侦听器。

this.$el.on('click', '.add-location-btn', this.addLocation);

确保你增加的这一行是作为initialize()函数的最后一行(在this.$el被分配以后)。

4、在EmployeeView中,定义addLocation 事件处理程序如下:

this.addLocation = function(event) {
  event.preventDefault();
  navigator.geolocation.getCurrentPosition(
      function(position) {
          alert(position.coords.latitude + ',' + position.coords.longitude);
      },
      function() {
          alert('Error getting location');
      });
  return false;
};

5、测试应用程序。

上一篇: 使用硬件加速 下一篇: 使用联系人 API