首页 > 解决方案 > 离子地理定位在android模拟器中不起作用

问题描述

我目前正在从事一个 Ionic 项目,我需要在该项目中获取外部 API。所以我决定使用 OpenWeatherMap API。问题:设法获取 Ionic 网站的位置,但是一旦导入到模拟器 API 中没有显示任何内容。我目前正在使用选项卡式导航。如果可以调查 tab1.page.ts 将不胜感激。谢谢你!!

离子模拟器 - 不显示

离子服务。工作和展示

tab1.page.ts

import { Component, OnInit } from '@angular/core';
import { Geolocation } from '@ionic-native/geolocation/ngx';
import { HttpClient } from '@angular/common/http';
import { Platform } from '@ionic/angular';
import { AndroidPermissions } from '@ionic-native/android-permissions/ngx'


@Component({
  selector: 'app-tab1',
  templateUrl: 'tab1.page.html',
  styleUrls: ['tab1.page.scss']
})
export class Tab1Page implements OnInit {

  id: string = "";
  place: string = "";
  type: string = "";
  icon: string = "";
  temperature: string = "";
  lat: any
  long: any


  constructor(public httpClient: HttpClient, public geolocation: Geolocation, public platform: Platform, private permission: AndroidPermissions) {
  }

  ngOnInit() {
    console.log("Hello there from tabs")
    this.geolocation.getCurrentPosition().then(position => {
      this.lat = position.coords.latitude
      this.long = position.coords.longitude
      console.log(this.lat)
      console.log(this.long)
    })

    this.getCurrentlocation()
    this.platform.ready().then(() => {
      this.requestpermissions();
      this.getCurrentlocation();
    });
  }

  async getCurrentlocation() {
    const position = await this.geolocation.getCurrentPosition().then((position) => {
      var latitude = position.coords.latitude;
      var longtitude = position.coords.longitude;
      this.getCurrentTemperature(latitude, longtitude);
      console.log(latitude)
      console.log(longtitude)
    })
  }

  getCurrentTemperature(latitude, longitude) {
    var url = "https://api.openweathermap.org/data/2.5/weather?lat=" + latitude + "&lon=" + longitude + "&appid=96ed99f24b94a5d5fd1f928c39feefa1"
    this.httpClient.get(url).subscribe((data) => {
      var obj = <any>data;
      this.place = obj.name;
      this.id = obj.id;
      console.log(this.id)
      this.type = obj.weather[0].main;
      this.icon = "http://openweathermap.org/img/w/" + obj.weather[0].icon + ".png";
      this.temperature = ((parseFloat(obj.main.temp) - 273.15).toFixed(2)).toString() + " Celsius";
    })
  }

  requestpermissions() {
    this.permission.checkPermission(this.permission.PERMISSION.ACCESS_COARSE_LOCATION).then((result) => {
      if (!result.hasPermission) {
        this.permission.requestPermission(this.permission.PERMISSION.ACCESS_COARSE_LOCATION);
        this.getCurrentlocation();
      }
    }, (err) => {
      this.permission.requestPermission(this.permission.PERMISSION.ACCESS_COARSE_LOCATION);
      this.getCurrentlocation();
    })
  }

}

标签: javascriptandroidionic-frameworkopenweathermap

解决方案


推荐阅读