Location search API - third generation

The meteoblue location search API resolves location names, postal codes, icao and iata codes to standardised WGS84 latitude and longitude coordinates that can be used with the meteoblue API. For a quick demonstration try our website, which also uses the API as well. Features:

Features

  • Search world-wide: "New York" or "Basel"
  • Postal codes : "4058" for Basel-City
  • ICAO and IATA airport codes: "LFSB" or "BSL" for EuroAirport Basel–Mulhouse
  • Fuzzy matching: "Berl" returns "Berlin"
  • Surrounding locations: "47.56°N 7.57°E" lists locations around Basel
  • Location awareness: "Ber" finds "Bern" for users around Bern and "Berlin" for users around Berlin
  • Intelligent results ranking: Based on location importance, population and location awareness
  • Localised results: "Bâle" is shown in French for "Basel"
  • Special character matching: German umlauts, Cyrillic and Arabic characters are transformed to Latin
  • Solid foundation: Based on most-recent GeoNames database
  • Performance: Responds within 0.1 seconds; ideal for AJAX applications
  • JSON + HTTPS

The meteoblue location search API is available for non-commercial use free of charge. For commercial use a usage agreement is required. Please contact us for further information.

Getting started

Retrieve location information

To query the location search API, simply send an HTTPS request. Let's search for Basel: https://www.meteoblue.com/en/server/search/query3?query=basel. The response should look similar to:

"query": "basel",
"currentPage": 1,
"itemsPerPage": 10,
"pages": 5,
"count": 42,
"orderBy": "ranker DESC",
"type": "name",
"results": [
{
  "name": "Basel",
  "iso2": "CH",
  "country": "Switzerland",
  "admin1": "Canton of Basel-Stadt",
  "lat": 47.558399,
  "lon": 7.57327,
  "asl": 279,
  "timezone": "Europe/Zurich",
  "population": 164488,
  "icao": "",
  "iata": "EAP",
  "postcodes": ["4000","4001","4031","..."],
  "url": "basel_switzerland_2661604"
},
{...}]

In this example "Basel" matches 42 entries ("count": 42). 10 entries are shown on each page ("itemsPerPage": 10 limit). There are 4 pages with 10 entries and the last page with 2 entries, so the matches are shown on 5 pages in total. Each result item contains detailed information about a location, most notably its localised name, country, elevation in meters above sea level ("asl") and coordinates ("lat" and "lon").

Every query consists of two parts: query string "/en/server/search/query3" and parameters "?query=basel". The query string can be modified to show results for a different locale (e.g. "/fr/" for french). "query3" indicates our third generation search API. Query parameter can be varied as specified below.

Example queries

The following example queries explain most features. You are also welcome to use the location-search API implementation on our website. We use JavaScript with AJAX and query this API for each keystroke.

Tip: The API returns only JSON formatted results. Some browser extensions format JSON in human readable way. For Example JSONView for Firefox for Chrome. Otherwise the output is a bit complicated to read.

Input parameter

Search queries support place names, postcodes, coordinates, iata and ICAO codes. The search algorithm automatically detects the type of the query and will return corresponding data. All input is fuzzy matched and allows typos to a certain degree. Special character like umlauts and most common coordinate-formats are detected and transformed. 

Parameter Type Description
query string Required. The search term. Attention: Special character should be url encoded
language 2 character Required. Language is defined in the URL prefix: https://www.meteoblue.com/de/... for results in german
iso2 2 character The country is specified by its ISO2 code. "DE" for germany
callback string Enables JSONP output with the specified callback function to bypass JavaScript same origin policy for older browsers

Sorting and pagination

The sorting algorithms have been trained for 2 years to achieve high usability and performance. Per default results are ordered by a ranker based on match-relevance, language, importance of a location (e.g. capital), population and distance to the current user. The results are highly depended on the users language and location. For short (1-2 character) queries the API will not return practical results as short character sequences match hundreds of thousands locations. We recommend at least 3 character queries for useful results.

The location search API returns for most queries more than 100 results. We recommend using pagination and display only 10-20 results at once. The API will never display or return more than 1000 results. The following GET parameter control basic ordering and pagination:

Parameter Type Description
orderBy string Default is "ranker DESC". The results can be sorted by every parameter of the location output. Append "ASC" for ascending or "DESC" for descending order, e.g. "asl DESC" to list the highest locations first.
page number Default is 1 (first page).
itemsPerPage number Default is 10. Specifies the number of items that are included in the response. Use the page parameter to get more results.

Output - Search function information

The returned JSON structure contains the following keys:

Name Type Description
type string Detected query type. "Name" or  "Coord"
iso2 2 character ISO2 country code.
query utf-8 string The search term.
orderBy string The column that has been used to sort the results, and "ASC" or "DESC" for ascending or descending order.
lat number Coordinate search only. The latitude value of the query.
lon number Coordinate search only. The longitude value of the query.
radius number Only relevant with coordinate search. The radius around the given coordinates that was used to search for locations in kilometers
count number Total number of results.
pages number Total number of pages.
itemsPerPage number Maximum amount of results per page.
currentPage number Number of the current page.

Output - Location information

Each location item in the "results" array contains:

Name Type Description
name utf-8 string The full localised name of the location, with special characters like ä or è.
iso2 2 character Country iso2 code
country utf-8 string Localised country name
admin1 utf-8 string Localised name of the first administrative area.
lat number The latitude of the location in decimal notation.
lon number The longitude of the location in decimal notation.
timezone string The timezone of the location.
population number Population
distance number Distance for coordinate search or geo-ip reference point
icao string ICAO code
iata string IATA code
postcodes string array List of postcode for each location
featureClass 1 character Feature class (see appendix)
featureCode string Feature code
url string meteoblue URL syntax used for links on our website

Examples

JSON with jQuery

The easiest way to retrieve location data in JavaScript is with jQuery and a JSON-formatted result.

var params = {
    query: "Hamburg",    // set parameter "query"
    iso2: "DE",       // set parameter "iso2"
};

$.ajax({
    url: "https://www.meteoblue.com/en/server/search/query3",
    data: params         // add parameter to ajax request
}).done(function(data) { printAllNames(data); });

function printAllNames(data) {
    var results = data.results;
    for(var i in results) {
        if(results.hasOwnProperty(i)) {
            console.log(results[i]["name"]);
        }
    }
}

This simple example will print the exact names of 10 locations that match the search term "Hamburg" in Germany ("iso2=DE") on the console.

Bypassing the JavaScript same-origin policy

We properly set all origin-policy headers. Older browsers do not allow a page to receive data from a different origin. With JSONP, this restriction is bypassed by wrapping a function call around the JSON data in the response. The example above only needs slight adjustments to work with JSONP.

 var params = {
    query: "Tokyo",
    iso2: "JP",
};

$.ajax({
    cache: true,           // enable caching of the results
    dataType: "jsonp",    // enable JSONP
    jsonpCallback: "printAllNames",  // use "printAllNames" as callback
    url: "https://www.meteoblue.com/en/server/search/query3",
    data: params           // add parameters to ajax request
});

function printAllNames(data) {
    var results = data.results;
    for(var i in results) {
        if(results.hasOwnProperty(i)) {
            console.log(results[i]["name"]);
        }
    }
}

As expected, the names of the first 10 locations that match the search Term "Tokyo“ will be printed in console. The "done" function, that was used before to pass the data to the "printAllNames" function is not required anymore, as it will be called directly from the response to the AJAX request.

PHP with cURL

This example shows how to use cURL in PHP with our location search API. The function "getLocationCoords" returns the latitude, longitude and elevation of the first match. Those three parameters should be used when requesting weather data from the meteoblue API.

private function getLocationCoords($query = "Basel", $iso2 = "CH") {
    $parameters = array("query" => $query, "iso2" => $iso2);
    $url = "https://www.meteoblue.com/en/server/search/query3?";
    $url .= http_build_query($parameters);

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $json = curl_exec($ch);
    $data = json_decode($json);

    $coords = array();
    $coords["lat"] = (float)$data->results["0"]->lat;
    $coords["lon"] = (float)$data->results["0"]->lon;
    $coords["asl"] = (int)$data->results["0"]->asl;
    /*
     * print_r($coords):
     * Array
     * (
     *     [lat] => 47.5582
     *     [lon] => 7.5881
     *     [asl] => 260
     * )
     */
    return $coords;
}

Appendix

Feature classification

featureClass Description
A Administrative Boundary Features
H Hydrographic Features
L Area Features
P Populated Place Features
S Spot Features
T Hypsographic Features

Feature codes

featureCode Description
ADM1 first-order administrative division
ADM2 second-order administrative division
ADM3 third-order administrative division
ADM4 fourth-order administrative division
ADM5 fifth-order administrative division
PCLI independent political entity
PCLD dependent political entity
PCLIX section of independent political entity
PCLS semi-independent political entity
TERR territory
PCLF freely associated state
PCL political entity
PPL populated place
PPLL populated locality
PPLC capital of a political entity
PPLA seat of a first-order administrative division
PPLA2 seat of a second-order administrative division
PPLA3 seat of a third-order administrative division
PPLA4 seat of a fourth-order administrative division
PPLX section of populated place
PPLS populated places
PPLCH historical capital of a political entity
PPLG seat of government of a political entity
AMUS amusement park
AIRP airport
MT mountain
MTS mountains
PK peak
PKS peaks
PAN pan
PANS pans
PASS pass
VALL valley
VALX section of valley
VALG hanging valley
VALS valleys
FLL waterfall(s)
DAM dam
PRK park
GLCR glacier(s)
CONT continent