如何获取当前位置的天气

Posted

技术标签:

【中文标题】如何获取当前位置的天气【英文标题】:How to get weather at current location 【发布时间】:2013-03-03 17:55:51 【问题描述】:

可能重复:

Get weather update of current location?

How can I get the weather in current location from Latitude and Longitude?

我正在开发一个应用程序,它可以更新当前位置的天气。我用谷歌搜索并找到了如何使用 Google API。但是现在 Google API 不可用了,我改用 Yahoo 天气。

我的问题:

    如何使用 Yahoo Weather API 获取天气

    教程或源代码

【问题讨论】:

【参考方案1】:

让我告诉你什么你不应该使用.. Google API(它已被停止)

http://thenextweb.com/google/2012/08/28/did-google-just-quietly-kill-private-weather-api/

然后,您还有其他选择,例如

雅虎天气 API

http://developer.yahoo.com/weather/

例如.. 要使用摄氏度和其他公制单位获取法国巴黎的预报: http://weather.yahooapis.com/forecastrss?w=615702&u=c

其他示例请访问链接 http://developer.yahoo.com/weather/#examples

WunderGround 天气 API

http://www.wunderground.com/weather/api/

另一个不错的替代方案是 Open Weather Map API ,它通过仅传递位置的纬度和经度来支持 JSON 输出。

http://openweathermap.org/wiki/API/JSON_API

【讨论】:

@MahmoudFarahat 由您决定,无论哪个解决您的目的都是最好的 能否请您建议如何在雅虎天气 API 中传递动态纬度。我正在获取当前位置的 lat long,当我尝试在 Yahoo 天气 API URL 中传递它时,它给了我 401,但是当我传递静态 lat long 时,它给了我结果。 URL : 'weather-ydn-yql.media.yahoo.com/forecastrss?lat=' + 纬度 + '&lon=' + 经度 + '&format=json&oauth_consumer_key=' + Appconstants.info.WEATHER_CONSUMER_KEY + '&oauth_signature_method=HMAC-SHA1&oauth_timestamp=' + timeStamp + '&oauth_nonce=+myAuthNonce+&oauth_version=1.0 &oauth_signature=+myauthSgnature' 请建议【参考方案2】:

我个人免费使用了这个 API,您可以通过邮政编码、邮政编码或经纬度检索任何位置的天气预报

Free Local Weather REST API

**注意:**Local Weather API 以 XML、JSON 和 CSV 格式返回天气数据,并包含温度、降水(降雨)、天气描述、天气图标和风速等天气元素。

**更新:**www.worldweatheronline.com/ api 不再免费。

试试这些

    accuweather.com https://openweathermap.org/ www.apixu.com

【讨论】:

非常感谢 Amitabh Sarkar Amitabh Sarkar - 它是免费的吗?我需要通过 lat-log 访问当地的天气报告。【参考方案3】:

以下是一组天气 API,您可以通过浏览器进行试验,然后以您喜欢的语言生成源代码:

https://live.temboo.com/library/keyword/weather/

完全披露:我在 Temboo 工作。

【讨论】:

【参考方案4】:

我个人使用过 OpenWeather API。它完全免费,您可以通过城市名称、邮政编码或经纬度等检索任何位置的天气预报。

<?php
 $city    = 'london';
    $jsonfile    = file_get_contents( 'http://api.openweathermap.org/data/2.5/weather?q=' . $city . '&units=metric&lang=en&appid=c0c4a4b4047b97ebc5948ac9c48c0559' );
    $jsondata    = json_decode( $jsonfile );
    $temp        = $jsondata->main->temp;
    $pressure    = $jsondata->main->pressure;
    $mintemp     = $jsondata->main->temp_min;
    $maxtemp     = $jsondata->main->temp_max;
    $wind        = $jsondata->wind->speed;
    $humidity    = $jsondata->main->humidity;
    $desc        = $jsondata->weather[0]->description;
    $maind       = $jsondata->weather[0]->main;
    $currentTime = time();
    ?>
    <style>
    body 
        font-family: Arial;
        font-size: 0.95em;
        color: #929292;
    
    
    
    .report-container 
        border: #E0E0E0 1px solid;
        padding: 20px 40px 40px 40px;
        border-radius: 2px;
        width: 550px;
        margin: 0 auto;
    
    
    .weather-icon 
        vertical-align: middle;
        margin-right: 20px;
    
    
    .weather-forecast 
        color: #212121;
        font-size: 1.2em;
        font-weight: bold;
        margin: 20px 0px;
    
    
    span.min-temperature 
        margin-left: 15px;
        color: #929292;
    
    
    .time 
        line-height: 25px;
    
    </style>
    <body>
    <div class="report-container">
            <h2><?php echo $jsondata->name; ?> Weather Status</h2>
            <div class="time">
                <div><?php echo date( 'l g:i a', $currentTime ); ?></div>
                <div><?php echo date( 'jS F, Y', $currentTime ); ?></div>
                <div><?php echo $desc; ?></div>
            </div>
            <div class="weather-forecast">
                <img
                    src="http://openweathermap.org/img/w/<?php echo $jsondata->weather[0]->icon; ?>.png"
                    class="weather-icon" /> <?php echo $mintemp; ?>°C<span
                    class="min-temperature"><?php echo $maxtemp; ?>°C</span>
            </div>
            <div class="time">
                <div>Humidity: <?php echo $humidity; ?> %</div>
                <div>Wind: <?php echo $wind; ?> km/h</div>
            </div>
        </div>
        </body>

【讨论】:

【参考方案5】:

OpenWeatherMap 是您可以使用的最佳天气开放 API:https://openweathermap.org/api

它提供免费的天气数据和预报 API,适用于任何制图服务,如网络和智能手机应用程序 它使用 JSON/XML 格式为您的应用提供天气数据。 它提供了大量有用的天气相关信息 包括当前天气,历史天气,预报,风, 云、气象站数据等 我们如何获取选定位置的天气信息? Openweathermap 提供了两种不同的模式来寻找城市。一种使用名称模式,另一种使用地理坐标。 免费使用

这是一个示例应用程序android-openweathermap-app

【讨论】:

【参考方案6】:

您可以在 android 中获取集成天气 API,但它需要一点关于解析 xml 响应的知识。

weather data to display current weather

【讨论】:

【参考方案7】:

添加到 build.gradle

implementation 'com.github.androdocs:Simple-HTTP-Request:v1.0'

XML

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_
android:layout_
android:background="@drawable/bg_gradient"
android:orientation="vertical"
android:padding="25dp">

<RelativeLayout
    android:id="@+id/mainContainer"
    android:layout_
    android:layout_
    android:visibility="visible">

    <LinearLayout
        android:id="@+id/addressContainer"
        android:layout_
        android:layout_
        android:gravity="center"
        android:orientation="vertical">

        <TextView
            android:textColor="#FFFFFF"
            android:id="@+id/address"
            android:layout_
            android:layout_
            android:text="DHAKA, BD"
            android:textSize="24dp" />

        <TextView
            android:textColor="#FFFFFF"
            android:id="@+id/updated_at"
            android:layout_
            android:layout_
            android:text="20 April 2012, 20:08 PM"
            android:textSize="14dp" />
    </LinearLayout>


    <LinearLayout
        android:id="@+id/overviewContainer"
        android:layout_
        android:layout_
        android:layout_centerInParent="true"
        android:orientation="vertical">

        <TextView
            android:textColor="#FFFFFF"
            android:id="@+id/status"
            android:layout_
            android:layout_
            android:layout_gravity="center"
            android:text="Clear Sky"
            android:textSize="18dp" />

        <TextView
            android:textColor="#FFFFFF"
            android:id="@+id/temp"
            android:layout_
            android:layout_
            android:layout_gravity="center"
            android:fontFamily="sans-serif-thin"
            android:text="29°C"
            android:textSize="90dp" />

        <LinearLayout
            android:layout_
            android:layout_
            android:gravity="center"
            android:orientation="horizontal">

            <TextView
                android:textColor="#FFFFFF"
                android:id="@+id/temp_min"
                android:layout_
                android:layout_
                android:text="Min Temp: 05:05 AM" />

            <Space
                android:layout_
                android:layout_ />

            <TextView
                android:textColor="#FFFFFF"
                android:id="@+id/temp_max"
                android:layout_
                android:layout_
                android:text="Max Temp: 05:05 PM" />
        </LinearLayout>

    </LinearLayout>


    <LinearLayout
        android:id="@+id/detailsContainer"
        android:layout_
        android:layout_
        android:layout_alignParentBottom="true"
        android:orientation="vertical">

        <LinearLayout
            android:layout_
            android:layout_
            android:orientation="horizontal"
            android:weightSum="3">

            <LinearLayout
                android:layout_
                android:layout_
                android:layout_weight="1"
                android:background="#3CF1EBF1"
                android:gravity="center"
                android:orientation="vertical"
                android:padding="8dp">

                <ImageView
                    android:layout_
                    android:layout_
                    android:src="@drawable/sunrise"
                    android:tint="#FFFFFF" />

                <Space
                    android:layout_
                    android:layout_ />

                <TextView
                    android:textColor="#FFFFFF"
                    android:layout_
                    android:layout_
                    android:text="Sunrise"
                    android:textSize="12dp" />

                <TextView
                    android:textColor="#FFFFFF"
                    android:id="@+id/sunrise"
                    android:layout_
                    android:layout_
                    android:text="06:40 AM"
                    android:textSize="14dp" />
            </LinearLayout>

            <Space
                android:layout_
                android:layout_ />

            <LinearLayout
                android:layout_
                android:layout_
                android:layout_weight="1"
                android:background="#3CF1EBF1"
                android:gravity="center"
                android:orientation="vertical"
                android:padding="8dp">

                <ImageView
                    android:layout_
                    android:layout_
                    android:src="@drawable/sunset"
                    android:tint="#FFFFFF" />

                <Space
                    android:layout_
                    android:layout_ />

                <TextView
                    android:textColor="#FFFFFF"
                    android:layout_
                    android:layout_
                    android:text="Sunset"
                    android:textSize="12dp" />

                <TextView
                     android:textColor="#FFFFFF"
                    android:id="@+id/sunset"
                    android:layout_
                    android:layout_
                    android:text="06:40 AM"
                    android:textSize="14dp" />
            </LinearLayout>

            <Space
                android:layout_
                android:layout_ />

            <LinearLayout
                android:layout_
                android:layout_
                android:layout_weight="1"
                android:background="#3CF1EBF1"
                android:gravity="center"
                android:orientation="vertical"
                android:padding="8dp">

                <ImageView
                    android:layout_
                    android:layout_
                    android:src="@drawable/wind"
                    android:tint="#FFFFFF" />

                <Space
                    android:layout_
                    android:layout_ />

                <TextView
                    android:textColor="#FFFFFF"
                    android:layout_
                    android:layout_
                    android:text="Wind"
                    android:textSize="12dp" />

                <TextView
                    android:textColor="#FFFFFF"
                    android:id="@+id/wind"
                    android:layout_
                    android:layout_
                    android:text="06:40 AM"
                    android:textSize="14dp" />
            </LinearLayout>
        </LinearLayout>

        <Space
            android:layout_
            android:layout_ />

        <LinearLayout
            android:layout_
            android:layout_
            android:orientation="horizontal"
            android:weightSum="3">

            <LinearLayout
                android:layout_
                android:layout_
                android:layout_weight="1"
                android:background="#3CF1EBF1"
                android:gravity="center"
                android:orientation="vertical"
                android:padding="8dp">

                <ImageView
                    android:layout_
                    android:layout_
                    android:src="@drawable/pressure"
                    android:tint="#FFFFFF" />

                <Space
                    android:layout_
                    android:layout_ />

                <TextView
                    android:textColor="#FFFFFF"
                    android:layout_
                    android:layout_
                    android:text="Pressure"
                    android:textSize="12dp" />

                <TextView
                    android:textColor="#FFFFFF"
                    android:id="@+id/pressure"
                    android:layout_
                    android:layout_
                    android:text="06:40 AM"
                    android:textSize="14dp" />
            </LinearLayout>

            <Space
                android:layout_
                android:layout_ />

            <LinearLayout
                android:layout_
                android:layout_
                android:layout_weight="1"
                android:background="#3CF1EBF1"
                android:gravity="center"
                android:orientation="vertical"
                android:padding="8dp">

                <ImageView
                    android:layout_
                    android:layout_
                    android:src="@drawable/humidity"
                    android:tint="#FFFFFF" />

                <Space
                    android:layout_
                    android:layout_ />

                <TextView
                    android:textColor="#FFFFFF"
                    android:layout_
                    android:layout_
                    android:text="Humidity"
                    android:textSize="12dp" />

                <TextView
                    android:textColor="#FFFFFF"
                    android:id="@+id/humidity"
                    android:layout_
                    android:layout_
                    android:text="06:40 AM"
                    android:textSize="14dp" />
            </LinearLayout>

            <Space
                android:layout_
                android:layout_ />

            <LinearLayout
                android:layout_
                android:layout_
                android:layout_weight="1"
                android:background="#3CF1EBF1"
                android:gravity="center"
                android:orientation="vertical"
                android:padding="8dp">

                <ImageView
                    android:layout_
                    android:layout_
                    android:src="@drawable/info"
                    android:tint="#FFFFFF" />

                <Space
                    android:layout_
                    android:layout_ />

                <TextView
                    android:textColor="#FFFFFF"
                    android:layout_
                    android:layout_
                    android:text="Created By"
                    android:textSize="12dp" />

                <TextView
                    android:textColor="#FFFFFF"
                    android:id="@+id/about"
                    android:layout_
                    android:layout_
                    android:text="AndroDocs"
                    android:textSize="14dp" />
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
</RelativeLayout>


<ProgressBar
    android:id="@+id/loader"
    android:layout_
    android:layout_
    android:layout_centerInParent="true"
    android:visibility="gone" />

<TextView
    android:id="@+id/errorText"
    android:layout_
    android:layout_
    android:layout_centerInParent="true"
    android:text="Something went wrong"
    android:visibility="gone" />

 public class WeatherActivity extends AppCompatActivity 
//    String CITY = "surat";
String API = "8118ed6ee68db2debfaaa5a44c832918";
String locality;
 TextView addressTxt, updated_atTxt, statusTxt, tempTxt, temp_minTxt, temp_maxTxt, 
sunriseTxt,   sunsetTxt, windTxt, pressureTxt, humidityTxt;

@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    if (Build.VERSION.SDK_INT >= 21) 
        getWindow().clearFlags(67108864);
        getWindow().setStatusBarColor(ContextCompat.getColor(this, 
R.color.weatheract));
    
    setContentView(R.layout.activity_weather);

    addressTxt = findViewById(R.id.address);
    updated_atTxt = findViewById(R.id.updated_at);
    statusTxt = findViewById(R.id.status);
    tempTxt = findViewById(R.id.temp);
    temp_minTxt = findViewById(R.id.temp_min);
    temp_maxTxt = findViewById(R.id.temp_max);
    sunriseTxt = findViewById(R.id.sunrise);
    sunsetTxt = findViewById(R.id.sunset);
    windTxt = findViewById(R.id.wind);
    pressureTxt = findViewById(R.id.pressure);
    humidityTxt = findViewById(R.id.humidity);

    LocationManager locationManager = (LocationManager) 
getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    if (ContextCompat.checkSelfPermission(this, 
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
            && ContextCompat.checkSelfPermission(this, 
Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) 

        Location location = 
locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, 
false));
        if (location != null) 
            getCity(location.getLatitude(), location.getLongitude());
        
    



private final void getCity(double d2, double d3) 
    List list;

    try 
        list = new Geocoder(getApplicationContext(), 
Locale.getDefault()).getFromLocation(d2, d3, 1);
        if (list != null && (!list.isEmpty())) 
            locality = ((Address) list.get(0)).getLocality();
            new weatherTask().execute();

        
     catch (NullPointerException e2) 

     catch (IOException e) 
        e.printStackTrace();
    


class weatherTask extends AsyncTask<String, Void, String> 
    @Override
    protected void onPreExecute() 
        super.onPreExecute();

        /* Showing the ProgressBar, Making the main design GONE */
        findViewById(R.id.loader).setVisibility(View.VISIBLE);
        findViewById(R.id.mainContainer).setVisibility(View.GONE);
        findViewById(R.id.errorText).setVisibility(View.GONE);
    

    protected String doInBackground(String... args) 
        String response = 
HttpRequest.excuteGet("https://api.openweathermap.org/data/2.5/weather?q=" + locality 
+ "&units=metric&appid=" + API);
        return response;
    

    @Override
    protected void onPostExecute(String result) 


        try 
            JSONObject jsonObj = new JSONObject(result);
            JSONObject main = jsonObj.getJSONObject("main");
            JSONObject sys = jsonObj.getJSONObject("sys");
            JSONObject wind = jsonObj.getJSONObject("wind");
            JSONObject weather = jsonObj.getJSONArray("weather").getJSONObject(0);

            Long updatedAt = jsonObj.getLong("dt");
            String updatedAtText = "Updated at: " + new SimpleDateFormat("dd/MM/yyyy 
hh:mm a", Locale.ENGLISH).format(new Date(updatedAt * 1000));
            String temp = main.getString("temp") + "°C";
            String tempMin = "Min Temp: " + main.getString("temp_min") + "°C";
            String tempMax = "Max Temp: " + main.getString("temp_max") + "°C";
            String pressure = main.getString("pressure");
            String humidity = main.getString("humidity");

            Long sunrise = sys.getLong("sunrise");
            Long sunset = sys.getLong("sunset");
            String windSpeed = wind.getString("speed");
            String weatherDescription = weather.getString("description");

            String address = jsonObj.getString("name") + ", " + 
sys.getString("country");


            /* Populating extracted data into our views */
            addressTxt.setText(address);
            updated_atTxt.setText(updatedAtText);
            statusTxt.setText(weatherDescription.toUpperCase());
            tempTxt.setText(temp);
            temp_minTxt.setText(tempMin);
            temp_maxTxt.setText(tempMax);
            sunriseTxt.setText(new SimpleDateFormat("hh:mm a", 
Locale.ENGLISH).format(new Date(sunrise * 1000)));
            sunsetTxt.setText(new SimpleDateFormat("hh:mm a", 
Locale.ENGLISH).format(new Date(sunset * 1000)));
            windTxt.setText(windSpeed);
            pressureTxt.setText(pressure);
            humidityTxt.setText(humidity);

            /* Views populated, Hiding the loader, Showing the main design */
            findViewById(R.id.loader).setVisibility(View.GONE);
            findViewById(R.id.mainContainer).setVisibility(View.VISIBLE);


         catch (JSONException e) 
            findViewById(R.id.loader).setVisibility(View.GONE);
            findViewById(R.id.errorText).setVisibility(View.VISIBLE);
        

    




【讨论】:

以上是关于如何获取当前位置的天气的主要内容,如果未能解决你的问题,请参考以下文章

django - 如何通过浏览器 IP 获取位置

如何将 placemark.locality 放入我的天气 API?

iOS定位和获取当前天气

如何在不使用谷歌地图和其他地图的情况下获取用户当前位置?

如何在自己的网页中加入天气预报

GraduateDesign-给APP添加获取位置信息和天气预报的功能(json)