• Tidak ada hasil yang ditemukan

PERTEMUAN KE 12 Aplikasi dengan Database (MySQL)

N/A
N/A
Protected

Academic year: 2021

Membagikan "PERTEMUAN KE 12 Aplikasi dengan Database (MySQL)"

Copied!
16
0
0

Teks penuh

(1)

PERTEMUAN KE – 12

Aplikasi dengan Database (MySQL)

A. TUJUAN

Mahasiswa diharapkan dapat memahami dan mengetahui tentang komponen widget, yaitu Webservice, mysql dan json yang digunakan pada aplikasi mobile.

B. TEORI SINGKAT

JSON (JavaScript Object Notation) adalah format pertukaran data yang ringan, mudah dibaca dan ditulis oleh manusia, serta mudah diterjemahkan dan dibuat (generate) oleh komputer. Format ini dibuat berdasarkan bagian dari Bahasa Pemprograman JavaScript, Standar ECMA-262 Edisi ke-3 – Desember 1999. JSON merupakan format teks yang tidak bergantung pada bahasa pemrograman apapun karena menggunakan gaya bahasa yang umum digunakan oleh programmer keluarga C termasuk C, C++, C#, Java, JavaScript, Perl, Python dll. Oleh karena sifat-sifat tersebut, menjadikan JSON ideal sebagai bahasa pertukaran-data.

Metode JSON dalam pengiriman data dilakukan, karena JSON memiliki beberapa kelebihan - kelebihan dibandingkan XML, kelebihan – kelebihan tersebut adalah:

1. Format Penulisan Untuk merepresentasikan sebuah struktur data yang rumit dan berbentuk hirarkis penulisan JSON relatif lebih terstruktur dan mudah.

2. Ukuran Ukuran karakter yang dibutuhkan JSON lebih kecil dibandingkan XML untuk data yang sama. Hal ini tentu berpengaruh pula pada kecepatan pertukaran data, walaupun tidak signifikan untuk data yang kecil, namun cukup berarti jika koneksi yang digunakan relatif lambat untuk mengakses aplikasi web kaya fitur yang memanfaatkan pertukaran data. Di sini JSON lebih unggul dibandingkan XML, kecuali jika data dikompresi terlebih dahulu sebelum dikirimkan, perbedaan JSON dan XML yang telah dikompresi tidaklah signifikan.

3. Browser Parsing Proses parsing merupakan proses pengenalan token atau bagian-bagian kecil dalam rangkaian dokumen XML/JSON. Contohnya, terdapat data text dalam format JSON. Data tersebut harus di-parsing terlebih dahulu sebelum dapat diakses dan dimanipulasi. Browser parsing berarti proses parsing yang terjadi pada sisi client/browser.

Melakukan browser parsing pada JSON lebih sederhana dibandingkan pada XML, JSON menggunakan function JavaScript eval() untuk melakukan parsing. Sementara dokumen XML di-parsing oleh XMLHttpRequest. Rata-rata survei menobatkan JSON sebagai pemenang jika diadu kecepatan parsingnya. JSON terbuat dari dua struktur:

1. Kumpulan pasangan nama/nilai. Pada beberapa bahasa, hal ini dinyatakan sebagai objek (object), rekaman (record), struktur (struct), kamus (dictionary), tabel hash (hash table), daftar berkunci (keyed list), atau associative array.

2. Daftar nilai terurutkan (an ordered list of values). Pada kebanyakan bahasa, hal ini dinyatakan sebagai larik (array), vektor (vector), daftar (list), atau urutan (sequence).

Struktur-struktur data ini disebut sebagai struktur data universal. Pada dasarnya, semua bahasa pemprograman moderen mendukung struktur data ini dalam bentuk yang sama maupun berlainan. Hal ini pantas disebut demikian karena format data mudah dipertukarkan dengan bahasa-bahasa pemprograman yang juga berdasarkan pada struktur data ini. JSON menggunakan bentuk sebagai berikut:

1. Objek. Objek adalah sepasang nama/nilai yang tidak terurutkan. Objek dimulai dengan { (kurung kurawal buka) dan diakhiri dengan } (kurung kurawal tutup). Setiap nama diikuti dengan : (titik dua) dan setiap pasangan nama/nilai dipisahkan oleh , (koma).

Gambar. Objek JSON

2. Larik. Larik adalah kumpulan nilai yang terurutkan. Larik dimulai dengan [ (kurung kotak buka) dan diakhiri dengan ] (kurung kotak tutup). Setiap nilai dipisahkan oleh , (koma).

Gambar. Larik JSON

3. Nilai. Nilai (value) dapat berupa sebuah string dalam tanda kutip ganda, atau angka, atau true atau false atau null, atau sebuah objek atau sebuah larik. Strukturstruktur tersebut dapat disusun bertingkat.

(2)

Gambar Nilai JSON

4. String. String adalah kumpulan dari nol atau lebih karakter Unicode, yang dibungkus dengan tanda kutip ganda. Di dalam string dapat digunakan backslash escapes "\" untuk membentuk karakter khusus. Sebuah karakter mewakili karakter tunggal pada string. String sangat mirip dengan string C atau Java.

Gambar. String JSON.

5. Angka Angka adalah sangat mirip dengan angka di C atau Java, kecuali format oktal dan heksadesimal tidak digunakan.

Gambar. Angka JSON

C. PRAKTIK

1. Dalam praktikum ini kita akan menggunakan database yang sudah tersedia di server umum. Kita akan membuat aplikasi cuaca.

2. Buat project baru. Kemudian buat sebuah layout.

3. activity dengan nama activity_main.xml. Kodingnya adalah sebagai berikut. (Perhatikan nama paketnya sesuaikan dengan yang anda buat)

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"

android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent"

(3)

android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="belajar1.coba.ningrum.cuaca.MainActivity"> <TextView android:id="@+id/textLokasi" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginTop="35dp" android:text="Lokasi" android:textAppearance="?android:attr/textAppearanceMedium" /> <EditText android:id="@+id/lokasi" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/textLokasi" android:layout_alignParentRight="true" android:hint="Inputkan Lokasi"

android:ems="10" /> <requestFocus /> <TextView android:id="@+id/textNegara" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textLokasi" android:layout_below="@+id/textLokasi" android:layout_marginTop="68dp" android:text="@string/country" android:textAppearance="?android:attr/textAppearanceSmall" /> <TextView android:id="@+id/textSuhu" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/textNegara" android:layout_marginTop="19dp" android:text="@string/temperature" android:textAppearance="?android:attr/textAppearanceSmall" /> <TextView android:id="@+id/textLembab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textSuhu" android:layout_below="@+id/textSuhu" android:layout_marginTop="32dp" android:text="@string/humidity" android:textAppearance="?android:attr/textAppearanceSmall" /> <TextView android:id="@+id/textTekanan" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textLembab" android:layout_below="@+id/textLembab" android:layout_marginTop="21dp" android:text="@string/pressure" android:textAppearance="?android:attr/textAppearanceSmall" /> <EditText android:id="@+id/suhu" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/textSuhu" android:layout_alignBottom="@+id/textSuhu" android:layout_alignLeft="@+id/negara" android:ems="10" /> <EditText android:id="@+id/kelembapan" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/textTekanan" android:layout_alignLeft="@+id/lokasi" android:ems="10" /> <Button

(4)

android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/negara" android:layout_below="@+id/lokasi" android:onClick="open" android:text="@string/weather"/> <ImageView android:id="@+id/gambarCuaca" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:adjustViewBounds="false" android:src="@drawable/clear" android:layout_below="@+id/textTekanan" android:layout_centerHorizontal="true"/> <EditText android:id="@+id/negara" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/textNegara" android:layout_alignBottom="@+id/textNegara" android:layout_alignLeft="@+id/kelembapan" android:ems="10" /> <EditText android:id="@+id/tekanan" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/textTekanan" android:layout_alignBottom="@+id/textTekanan" android:layout_alignLeft="@+id/kelembapan" android:ems="10" /> <TextView android:id="@+id/Jam" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="85dp" android:text="01/01/2017 00:00:00 AM" /> </RelativeLayout> Hasilnya

4. Dan tambahkan pada file MainActivity.java sehingga menjadi sebagai berikut import android.os.Bundle;

import android.support.v7.app.AppCompatActivity; import android.view.View;

(5)

import android.widget.ImageView; import android.widget.TextView; import java.text.SimpleDateFormat; import java.util.Calendar;

public class MainActivity extends AppCompatActivity {

private String url1 = "http://api.openweathermap.org/data/2.5/weather?q="; private EditText location, country, humidity, pressure,temperature;

private ImageView gambar; private HandleJSON obj; private TextView jam; @Override

protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

location = (EditText)findViewById(R.id.lokasi); country = (EditText)findViewById(R.id.negara); temperature = (EditText)findViewById(R.id.suhu); humidity = (EditText)findViewById(R.id.kelembapan); pressure = (EditText)findViewById(R.id.tekanan); jam = (TextView)findViewById(R.id.Jam);

gambar = (ImageView) findViewById(R.id.gambarCuaca); }

public void open(View view){

String url = location.getText().toString().trim();

String finalUrl = url1+url+"&APPID=d9793cc166c0aa14865c2b34a7f9e8a9"; country.setText(finalUrl);

obj = new HandleJSON(finalUrl); obj.fetchJSON();

while(obj.parsingComplete);

country.setText(obj.getCountry());

temperature.setText(String.valueOf(obj.getTemperature()+"°C")); humidity.setText(obj.getHumidity()+" %");

pressure.setText(obj.getPressure()+" hPa"); jam.setText(getTime());

Imageicon(obj.getIcon()); }

public static String getTime() {

SimpleDateFormat sdf1 = new SimpleDateFormat("d/M/yyyy h:m:s a"); Calendar calendar = Calendar.getInstance();

String strdate1 = sdf1.format(calendar.getTime()); return strdate1;

}

private void Imageicon (String image){ if(image.equals("01d")){

gambar.setImageResource(R.drawable.clear); }

else if (image.equals("01n")){

gambar.setImageResource(R.drawable.ntclear); }

else if (image.equals("02d")){

gambar.setImageResource(R.drawable.mostlysunny); }

else if (image.equals("02n")){

gambar.setImageResource(R.drawable.ntmostlycloudy); }

else if (image.equals("03d") ||image.equals("03n") ){ gambar.setImageResource(R.drawable.cloudy); }

else if (image.equals("04d") || image.equals("04n") ){ gambar.setImageResource(R.drawable.fog);

}

else if (image.equals("09d") || image.equals("10d") || image.equals("09n") || image.equals("10n")){ gambar.setImageResource(R.drawable.chancerain);

}

else if (image.equals("11d") || image.equals("11n")){ gambar.setImageResource(R.drawable.chancetstorms); }

else if (image.equals("13d") || image.equals("13n")){ gambar.setImageResource(R.drawable.chanceflurries); }

} }

(6)

5. Buat sebuah java class dengan nama HandleJSON.java. Kodingnya sebagai berikut. import org.json.JSONArray; import org.json.JSONObject; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL;

public class HandleJSON {

private String country = "country"; private Integer temperature = 0; private String humidity = "humidity"; private String pressure = "pressure"; private String urlString = "null"; private String icon = "icon";

private String description ="description";

public volatile boolean parsingComplete = true; public HandleJSON(String url){

this.urlString = url; }

public String getCountry(){ return country;

}

public Integer getTemperature(){ temperature = temperature -273; return temperature;

}

public String getHumidity(){ return humidity;

}

public String getPressure(){ return pressure;

}

public String getIcon(){ return icon;

}

public String getDescription(){ return description;

}

public void readAndParseJSON(String in){ try{

JSONObject reader = new JSONObject(in); JSONObject sys = reader.getJSONObject("sys"); country = sys.getString("country");

JSONObject main = reader.getJSONObject("main"); temperature = main.getInt("temp");

pressure = main.getString("pressure"); humidity = main.getString("humidity");

JSONArray weather = reader.getJSONArray("weather"); JSONObject Weather = weather.getJSONObject(0); icon = Weather.getString("icon");

description = Weather.getString("description"); parsingComplete = false;

}catch (Exception e){ e.printStackTrace(); }

}

public void fetchJSON(){

Thread thread = new Thread(new Runnable(){ public void run(){

try{

URL url = new URL(urlString);

HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000/*miliseconds*/); conn.setConnectTimeout(15000/*miliseconds*/); conn.setRequestMethod("GET"); conn.setDoInput(true); conn.connect();

InputStream stream = conn.getInputStream(); String data = convertStreamToString(stream); readAndParseJSON(data);

(7)

}catch(Exception e){ e.printStackTrace(); } } }); thread.start(); }

private String convertStreamToString(java.io.InputStream is) {

// TODO Auto-generated method stub

java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A"); return s.hasNext() ? s.next() : "";

} }

6. Tambahkan pada resouce string, sehingga menjadi sebagai berikut (pada app name tambahkan nomer mahasiswa anda)

<resources>

<string name="app_name">Cuaca</string>

<string name="action_settings">Settings</string> <string name="hello_world">Hello world!</string> <string name="location">Lokasi</string>

<string name="country">Negara</string> <string name="temperature">Suhu</string> <string name="humidity">Kelembaban</string> <string name="pressure">Tekanan</string> <string name="weather">Cuaca</string> </resources>

7. Tambahkan internet permission pada Android Manifest.

8. Coba jalankan dan amati hasilnya. Jelaskan jalannya program.

D. LATIHAN

Latihan diberikan oleh dosen pengampu pada saat praktikum. Dikerjakan di laboratorium pada jam praktikum.

E. TUGAS

Tugas diberikan oleh dosen pengampu pada akhir praktikum. Dikerjakan di rumah dan dilampirkan pada laporan.

(8)

LAMPIRAN

To get access to weather API you need an API key whatever account

you choose from Free to Enterprise.

OpenWeatherMap. (https://openweathermap.org)

How to use API key in API call

Description:

To get access to weather API you need an API key whatever account you chose from Free to Enterprise. Activation of an API key for Free and Startup plans takes 10 minutes. For other tariff plans it is 10 to 60 minutes.

We keep right to not to process API requests without API key. API call:

http://api.openweathermap.org/data/2.5/forecast?id=524901&APPID={APIKEY} Parameters:

APPID {APIKEY} is your unique API key

Example of API call:

api.openweathermap.org/data/2.5/forecast?id=524901&APPID=1111111111

How to get accurate API response

1 Do not send requests more than 1 time per 10 minutes from one device/one API key. Normally the weather is not changing so frequently.

2 Use the name of the server as api.openweathermap.org. Please never use the IP address of the server. 3 Call API by city ID instead of city name, city coordinates or zip code. In this case you get precise respond exactly for your city. The cities' IDs can be found in the following file: Cities' IDs list.

4 Free and Startup accounts have limitation of capacity and data availability. If you do not get respond from server do not try to repeat your request immediately, but only after 10 min. Also we recommend to store your previous request data.

Call current weather data for one location

Please remember that all Examples of API calls that listed on this page are just

samples and do not have any connection to the real API service!

By city name

Description:

You can call by city name or city name and country code. API responds with a list of results that match a searching word.

There is a possibility to receive a central district of the city/town with its own parameters (geographic coordinates/id/name) in API response. Example

(9)

API call:

api.openweathermap.org/data/2.5/weather?q={city name}

api.openweathermap.org/data/2.5/weather?q={city name},{country code} Parameters:

q city name and country code divided by comma, use ISO 3166 country codes Examples of API calls:

api.openweathermap.org/data/2.5/weather?q=London api.openweathermap.org/data/2.5/weather?q=London,uk

By city ID

Description:

You can call by city ID. API responds with exact result.

List of city ID city.list.json.gz can be downloaded here http://bulk.openweathermap.org/sample/ We recommend to call API by city ID to get unambiguous result for your city.

Parameters: id City ID

Examples of API calls:

api.openweathermap.org/data/2.5/weather?id=2172797

By geographic coordinates

API call:

api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon} Parameters:

lat, lon coordinates of the location of your interest Examples of API calls:

api.openweathermap.org/data/2.5/weather?lat=35&lon=139 API respond: {"coord":{"lon":139,"lat":35}, "sys":{"country":"JP","sunrise":1369769524,"sunset":1369821049}, "weather":[{"id":804,"main":"clouds","description":"overcast clouds","icon":"04n"}], "main":{"temp":289.5,"humidity":89,"pressure":1013,"temp_min":287.04,"temp_max":292.04}, "wind":{"speed":7.31,"deg":187.002}, "rain":{"3h":0}, "clouds":{"all":92}, "dt":1369824698, "id":1851632, "name":"Shuzenji", "cod":200}

By ZIP code

Description:

(10)

Please note if country is not specified then the search works for USA as a default. API call:

api.openweathermap.org/data/2.5/weather?zip={zip code},{country code} Examples of API calls:

api.openweathermap.org/data/2.5/weather?zip=94040,us Parameters:

zip zip code API respond: {"coord":{"lon":-122.09,"lat":37.39}, "sys":{"type":3,"id":168940,"message":0.0297,"country":"US","sunrise":1427723751,"sunset":1427768967}, "weather":[{"id":800,"main":"Clear","description":"Sky is Clear","icon":"01n"}], "base":"stations", "main":{"temp":285.68,"humidity":74,"pressure":1016.8,"temp_min":284.82,"temp_max":286.48}, "wind":{"speed":0.96,"deg":285.001}, "clouds":{"all":0}, "dt":1427700245, "id":0, "name":"Mountain View", "cod":200}

Call current weather data for several cities

Cities within a rectangle zone

Description:

JSON returns the data from cities within the defined rectangle specified by the geographic coordinates. Parameters:

bbox bounding box [lon-left,lat-bottom,lon-right,lat-top,zoom] callback javascript functionName

cluster use server clustering of points. Possible values are [yes, no] lang language [ru, en ... ]

Examples of API calls:

http://api.openweathermap.org/data/2.5/box/city?bbox=12,32,15,37,10

Cities in cycle

Description:

JSON returns data from cities laid within definite circle that is specified by center point ('lat', 'lon') and expected number of cities ('cnt') around this point. The default number of cities is 10, the maximum is 50. Parameters:

(11)

lon longitude

callback functionName for JSONP callback.

cluster use server clustering of points. Possible values are [yes, no] lang language [en , ru ... ]

cnt number of cities around the point that should be returned Examples of API calls:

http://api.openweathermap.org/data/2.5/find?lat=55.5&lon=37.5&cnt=10

Call for several city IDs

Parameters: id City ID

Examples of API calls:

http://api.openweathermap.org/data/2.5/group?id=524901,703448,2643743&units=metric The limit of locations is 20.

NOTE: A single ID counts as a one API call! So, the above example is treated as a 3 API calls.

Bulk downloading

Description:

We provide number of bulk files with current weather and forecasts. More information is on the Bulk page Bulk downloading is available not for all accounts. To get more information please refer to the price. Examples of bulk files:

http://bulk.openweathermap.org/sample/

Weather parameters in API respond

If you do not see some of the parameters in your API respond it means that these weather phenomena are just not happened for the time of measurement for the city or location chosen. Only really measured or calculated data is displayed in API respond.

JSON

Example of API respond:

{"coord": {"lon":145.77,"lat":-16.92}, "weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04n"}], "base":"cmc stations", "main":{"temp":293.25,"pressure":1019,"humidity":83,"temp_min":289.82,"temp_max":295.37}, "wind":{"speed":5.1,"deg":150},

(12)

"clouds":{"all":75}, "rain":{"3h":3}, "dt":1435658272, "sys":{"type":1,"id":8166,"message":0.0166,"country":"AU","sunrise":1435610796,"sunset":1435650870}, "id":2172797, "name":"Cairns", "cod":200} Parameters:  coord

o coord.lon City geo location, longitude

o coord.lat City geo location, latitude

 weather (more info Weather condition codes)

o weather.id Weather condition id

o weather.main Group of weather parameters (Rain, Snow, Extreme etc.)

o weather.description Weather condition within the group

o weather.icon Weather icon id

 base Internal parameter  main

o main.temp Temperature. Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.

o main.pressure Atmospheric pressure (on the sea level, if there is no sea_level or grnd_level

data), hPa

o main.humidity Humidity, %

o main.temp_min Minimum temperature at the moment. This is deviation from current temp

that is possible for large cities and megalopolises geographically expanded (use these parameter optionally). Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.

o main.temp_max Maximum temperature at the moment. This is deviation from current temp

that is possible for large cities and megalopolises geographically expanded (use these parameter optionally). Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.

o main.sea_level Atmospheric pressure on the sea level, hPa

o main.grnd_level Atmospheric pressure on the ground level, hPa

 wind

o wind.speed Wind speed. Unit Default: meter/sec, Metric: meter/sec, Imperial: miles/hour.

o wind.deg Wind direction, degrees (meteorological)

 clouds

o clouds.all Cloudiness, %

 rain

o rain.3h Rain volume for the last 3 hours

 snow

o snow.3h Snow volume for the last 3 hours

 dt Time of data calculation, unix, UTC  sys

o sys.type Internal parameter

o sys.id Internal parameter

o sys.message Internal parameter

o sys.country Country code (GB, JP etc.)

o sys.sunrise Sunrise time, unix, UTC

o sys.sunset Sunset time, unix, UTC

 id City ID  name City name  cod Internal parameter

XML

(13)

<current>

<city id="2643741" name="City of London"> <coord lon="-0.09" lat="51.51">

<country>GB</country>

<sun rise="2015-06-30T03:46:57" set="2015-06-30T20:21:12"> </city>

<temperature value="72.34" min="66.2" max="79.88" unit="fahrenheit"/> <humidity value="43" unit="%">

<pressure value="1020" unit="hPa"> <wind>

<speed value="7.78" name="Moderate breeze"> <direction value="140" code="SE" name="SouthEast"> </wind>

<clouds value="0" name="clear sky"> <visibility value="10000">

<precipitation mode="no">

<weather number="800" value="Sky is Clear" icon="01d"> <lastupdate value="2015-06-30T08:36:14">

</current>

Parameters:  city

o city.idCity ID

o city.name City name

o city.coord

 city.coord.lon City geo location, longitude

 city.coord.lat City geo location, latitude

o city.country Country code (GB, JP etc.)

o city.sun

 city.sun.rise Sunrise time

 city.sun.set Sunset time

 temperature

o temperature.value Temperature

o temperature.min Minimum temperature at the moment of calculation. This is deviation from

'temp' that is possible for large cities and megalopolises geographically expanded (use these parameter optionally).

o temperature.max Maximum temperature at the moment of calculation. This is deviation

from 'temp' that is possible for large cities and megalopolises geographically expanded (use these parameter optionally).

o temperature.unit Unit of measurements. Possilbe valure is Celsius, Kelvin, Fahrenheit.

 humidity

o humidity.valueHumidity value

o humidity.unit %

 pressure

o pressure.valuePressure value

o pressure.unit hPa

 wind

o wind.speed

 wind.speed.valueWind speed, mps

 wind.speed.name Type of the wind

o wind.direction

 wind.direction.valueWind direction, degrees (meteorological)

 wind.direction.code Code of the wind direction. Possilbe value is WSW, N, S etc.

 wind.direction.name Full name of the wind direction.

(14)

o clouds.valueCloudiness

o clouds.name Name of the cloudiness

 visibility

o visibility.valueVisibility, meter

 precipitation

o precipitation.value Precipitation, mm

o precipitation.mode Possible values are 'no", name of weather phenomena as 'rain', 'snow'

 weather

o weather.number Weather condition id

o weather.value Weather condition name

o weather.icon Weather icon id

 lastupdate

o lastupdate.value Last time when data was updated

List of weather condition codes

List of weather condition codes with icons (range of thunderstorm, drizzle, rain, snow, clouds, atmosphere including extreme conditions like tornado, hurricane etc.)

Min/max temperature in current weather API and forecast API

Please, do not confuse min/max parameters in current weather API and forecast API. In current weather API temp_min and temp_max are optional parameters mean min / max temperature in the city at the current moment to see deviation from current temp just for your reference. For large cities and megalopolises geographically expanded it might be applicable. In most cases

both temp_min and temp_max parameters have the same volume as 'temp'. Please, use temp_min and temp_max parameters in current weather API optionally.

Example of current weather API respond:

"main":{

"temp":306.15, //current temperature "pressure":1013,

"humidity":44,

"temp_min":306, //min current temperature in the city "temp_max":306 //max current temperature in the city },

For comparison look at example of daily forecast weather API respond:

"dt":1406080800, "temp":{

"day":297.77, //daily averaged temperature "min":293.52, //daily min temperature "max":297.77, //daily max temperature "night":293.52, //night temperature "eve":297.77, //evening temperature "morn":297.77}, //morning temperature

(15)

Other features

Format

Description:

JSON format is used by default. To get data in XML or HTML formats just set up mode = xml or html. Parameters:

mode - possible values are xml and html. If mode parameter is empty the format is JSON by default. Examples of API calls:

JSON api.openweathermap.org/data/2.5/weather?q=London

XML api.openweathermap.org/data/2.5/weather?q=London&mode=xml HTML api.openweathermap.org/data/2.5/weather?q=London&mode=html

Search accuracy

Description:

You can use our geocoding system to find cities by name, country, zip-code or geographic coordinates. You can call also by part of the city name. To make the result more accurate just put the city name and country divided by comma.

To set the accuracy level either use the 'accurate' or 'like' type parameter. 'accurate' returns exact match values. 'like' returns results by searching for that substring.

Call API by city ID instead of city name, city coordinates or zip code. In this case you get precise respond exactly for your city.

Parameters: like close result

accurate accurate result Examples of API calls:

Like api.openweathermap.org/data/2.5/find?q=London&type=like&mode=xml

Accurate api.openweathermap.org/data/2.5/find?q=London&type=accurate&mode=xml

Units format

Description:

Standard, metric, and imperial units are available. Parameters:

units metric, imperial. When you do not use units parameter, format is Standard by default. Temperature is available in Fahrenheit, Celsius and Kelvin units.

 For temperature in Fahrenheit use units=imperial  For temperature in Celsius use units=metric

 Temperature in Kelvin is used by default, no need to use units parameter in API call List of all API parameters with units openweathermap.org/weather-data

Examples of API calls:

standard api.openweathermap.org/data/2.5/find?q=London

metric api.openweathermap.org/data/2.5/find?q=London&units=metric imperial api.openweathermap.org/data/2.5/find?q=London&units=imperial

(16)

Multilingual support

Description:

You can use lang parameter to get the output in your language. We support the following languages that you can use with the corresponded lang values:

Arabic - ar, Bulgarian - bg, Catalan - ca, Czech - cz, German - de, Greek - el, English - en, Persian (Farsi) - fa, Finnish - fi, French - fr, Galician - gl, Croatian - hr, Hungarian - hu, Italian - it, Japanese - ja, Korean - kr, Latvian - la, Lithuanian - lt, Macedonian - mk, Dutch - nl, Polish - pl, Portuguese - pt, Romanian - ro, Russian - ru, Swedish - se, Slovak - sk, Slovenian - sl, Spanish - es, Turkish - tr, Ukrainian - ua, Vietnamese - vi, Chinese Simplified - zh_cn, Chinese Traditional - zh_tw.

NOTE: Translation is only applied for the "description" field. API call:

http://api.openweathermap.org/data/2.5/forecast/daily?id=524901&lang={lang} Parameters:

lang language code Examples of API calls:

http://api.openweathermap.org/data/2.5/forecast/daily?id=524901&lang=zh_cn

Call back function for JavaScript code

Description:

To use JavaScript code you can transfer callback functionName to JSONP callback. Examples of API calls:

api.openweathermap.org/data/2.5/weather?q=London,uk&callback=test  Call current weather data for one location

o By city name

o By city ID

o By geographic coordinates

o By ZIP code

 Call current weather data for several cities

o Cities within a rectangle zone

o Cities in cycle

o Call for several city IDs  Bulk downloading

 Parameters of API respond

o JSON

o XML

o List of condition codes

o Min/max temperature in current weather API and forecast API  Other features

o Format

o Search accuracy

o Units format

o Multilingual support

Gambar

Gambar Nilai JSON

Referensi

Dokumen terkait

nilai ajaran Sunan Drajat; 3) tahap development berisi proses validasi dan uji coba produk; 4) tahapan implementation berisi penggunaan di lapangan dengan tujuan untuk

Cola adalah minuman yang digemari oleh orang orang, dari anak-anak, remaja hingga dewasa.. Karena rasanya yang segar dan nikmat, cola cocok di nikmati waktu siang hari,

Dengan menggunakan uji t, hasil penelitian ini menunjukkan bahwa iB-VACA memiliki pengaruh yang signifikan terhadap ROA yang berarti bahwa nilai iB-VACA ( Capital Employed )

Induk ikan lele SANGKURIANG yang akan digunakan dalam kegiatan proses produksi harus tidak berasal dari satu keturunan dan memiliki karakteristik kualitatif dan kuantitatif yang

1.3 Program REDD+ memerlukan Persetujuan atas dasar informasi di awal tanpa paksaan (Padiatapa) dari masyarakat adat dan masyarakat setempat untuk segala kegiatan

Dalam Undang-Undang ini ditetapkan bahwa Sistem Perencanaan Pembangunan Nasional adalah satu kesatuan tata cara perencanaan pembangunan untuk menghasilkan rencana pembangunan

Struktur jenis lamun pada setiap stasiun penelitian di perairan pantai Mara’bombang, memperlihatkan komposisi jenis lamun yang relatif berbeda, parameter hasil

Penduduk WNA yang memiliki Izin Tinggal Terbatas atau WNA yang memiliki Izin Tinggal Tetap yang akan pindah ke Luar Negeri sebagaimana dimaksud dalam Pasal 36 huruf b