メインコンテンツまでスキップ

Weather conditions

MapboxWeatherApi provides a single function getConditions , which allows retrieving multiple types of weather conditions:

  • Current conditions
  • Hourly forecast
  • Daily forecast
  • Route-based forecast

To request a specific type of weather condition, use the corresponding WeatherQuery Each WeatherQuery instance allows specifying the required weather condition fields for a given request. The requested fields will be available as a result in WeatherCondition.WeatherFields

Each WeatherQuery has a distinct set of available fields. For example:

  • WeatherQuery.Daily supports only TemperatureMin and TemperatureMax.
  • WeatherQuery.Current includes a broader range of parameters, such as Temperature, CloudCover, and WindSpeed.

If no specific fields are defined, all available fields for the given query type will be included in the response.

The table below outlines all possible fields across different queries:

FieldDescription
TemperatureTemperature in defined unit of measure.

Units: Expressed in fahrenheit when units=Imperial, expressed in celsius when units=Metric
Range: -140 to 140
TemperatureFeelsLikeAn apparent temperature in defined unit of measure. It represents what the air temperature “feels like” on exposed human skin due to the combined effect of the wind chill or heat index.

Units: Expressed in fahrenheit when units=Imperial, expressed in celsius when units=Metric
Range: -140 to 140
TemperatureMinThe midnight to midnight daily minimum temperature for the given day.

Units: Expressed in fahrenheit when units=Imperial, expressed in celsius when units=Metric
Range: -140 to 140
TemperatureMaxThe midnight to midnight daily maximum temperature for the given day.

The TemperatureMin and TemperatureMax fields encapsulate the absolute high and low temperatures within a calendar day defined by a midnight to midnight period. These values can provide a high or low temperature that occurred in the past within the provided day.

Units: Expressed in fahrenheit when units=Imperial, expressed in celsius when units=Metric
Range: -140 to 140
CloudCoverCloud cover expressed as a percentage.

Range: 0 to 100
DewPointThe temperature which air must be cooled at constant pressure to reach saturation. The Dewpoint is also an indirect measure of the humidity of the air. The Dewpoint will never exceed the Temperature. When the Dewpoint and Temperature are equal, clouds or fog will typically form. The closer the values of Temperature and Dewpoint, the higher the relative humidity.

Units: Expressed in fahrenheit when units=Imperial, expressed in celsius when units=Metric
Range: -80 to 100 (°F) or -62 to 37 (°C)
IsDayTimeDaytime or nighttime of the local apparent time of the location.

Range: true or false
HumidityThe relative humidity of the air, which is defined as the ratio of the amount of water vapor in the air to the amount of vapor required to bring the air to saturation at a constant temperature. Humidity is always expressed as a percentage.

Range: 0 to 100
PressureSeaLevelMean sea level pressure in millibars. In other words, the average barometric pressure at sea level.

Range: Millibars precise to 1/10th mb
PressureSurfaceLevelBarometric pressure is the pressure exerted by the atmosphere at the Earth’s surface due to the weight of the air. Altitude can be determined based on the measurement of barometric pressure. The lower the pressure, the greater the altitude.

Units: Expressed in inches of mercury when units=Imperial, expressed in millibars when units=Metric
Range: Inches of mercury precise to hundredths; Millibars precise to 1/10th mb
VisibilityThe horizontal visibility at the observation point. Visibilities can be reported as fractional values particularly when visibility is less than 2 miles. Visibilities greater than 10 statute miles(16.1 kilometers) which are considered “unlimited” are reported as “999”. You can also find visibility values that equal zero. This occurrence is not wrong. Dense fogs and heavy snows can produce values near zero. Fog, smoke, heavy rain and other weather phenomena can reduce visibility to near zero miles or kilometers.

Units: Expressed in miles when units=Imperial, expressed in kilometer when units=Metrical
Range: 0 to 999 or null
WindSpeedThe wind information reported in the current conditions corresponds to a 10-minute average called the sustained wind speed. Sudden or brief variations in the wind speed are called “wind gusts” and are reported in a separate data field.

Units: Expressed in miles per hour when units=Imperial, expressed in kilometers per hour when units=Metric
WindGustThis data field contains information about sudden and temporary variations of the average Wind Speed. The report always shows the maximum wind gust speed recorded during the observation period.

Units: Expressed in miles per hour when units=Imperial, expressed in kilometers per hour when units=Metric
WindDirectionThe magnetic wind direction from which the wind blows expressed in degrees. The magnetic direction varies from 0 to 359 degrees, where 0° indicates the North, 90° the East, 180° the South, 270° the West, and so forth.

Range: 0 to 359, in 10 degree intervals
WeatherPhraseA text description of observed weather conditions accompanying the IconCode field.

Range: 32 character phrase (Character limit applies to English phrases only. For other languages, which you can set through locale option, this phrase may exceed 32 characters)
IconCodeThe data field shows the icon number that is matched to represent the observed weather conditions. IconCode list located on the weather icons page.
PrecipitationRateOne hour rolling hour liquid precip amount. The amounts presented are a rolling time through the request time.

Units: Expressed in inches when units=Imperial, expressed in millimeters when units=Metric
PrecipitationProbabilityHourly maximum probability of precipitation

Range: 0 to 100
PrecipitationTypeThe short text describing the expected type accumulation associated with the PrecipitationProbability field.
SnowRateOne hour snowfall amount. The amounts presented are a rolling time through the request time.

Units: Expressed in inches when units=Imperial, expressed in millimeters when units=Metric

Understanding WeatherResult Structure

The getConditions method may return multiple WeatherResult objects. The number of results depends on the type of query. As of this time, only WeatherAlongRoute can return multiple results — each representing weather conditions at a specific location along the route.

Each WeatherResult contains one or more WeatherCondition objects. A WeatherCondition represents a set of weather fields for a specific moment in time, depending on the type of query:

  • A current weather query will return a single WeatherCondition for the present moment.
  • Hourly and daily forecast queries may return multiple WeatherCondition instances, based on the requested time interval.

Note that WeatherCondition.warning is only available for WeatherQuery.WarningsAlongRoute

Current conditions

Current weather conditions are generated on demand at the time of the request. They integrate multiple meteorological data sources to provide precise real-time weather information for the specified location.

To construct a query for current conditions, use the corresponding builder: WeatherQuery.Current.Builder:

val location: Point = Point.fromLngLat(61.37, 55.15)
// Setting up all available fields to demonstrate all possible values.
// You can use only those that are necessary for your use case
val currentQuery = WeatherQuery.Current.Builder(location)
.fields(
listOf(
Current.Fields.Temperature,
Current.Fields.TemperatureFeelsLike,
Current.Fields.CloudCover,
Current.Fields.DewPoint,
Current.Fields.IsDayTime,
Current.Fields.Humidity,
Current.Fields.PressureSeaLevel,
Current.Fields.Visibility,
Current.Fields.WindSpeed,
Current.Fields.WindGust,
Current.Fields.WindDirection,
Current.Fields.WeatherPhrase,
Current.Fields.IconCode,
Current.Fields.PrecipitationRate,
Current.Fields.PressureSurfaceLevel,
Current.Fields.SnowRate,
),
)
.build()
val fields = weatherApi.getConditions(currentQuery).fold(
onSuccess = {
it.firstOrNull()?.conditions?.firstOrNull()?.fields
},
onFailure = {
Log.e("Weather", it.message.orEmpty(), it)
null
},
)

val temperature = fields?.temperature
val feelsLike = fields?.temperatureFeelsLike

Log.d("Weather", "Current temperature: $temperature, feels like: $feelsLike")

Hourly forecast

This data provides weather forecasts for up to 12 hours ahead for the requested locations. Even though getConditions returns a list of WeatherResult, the actual result includes only one item related to the provided location.

The WeatherResult contains a list of WeatherCondition instances, where each item represents the predicted weather at a full-hour mark. If no interval is specified, the result includes 12 items, each corresponding to one of the next 12 hours. The forecasted hour can be determined using WeatherCondition.dateTime.

For example, to retrieve precipitation probability, precipitation type, and temperature at a destination point upon arrival, use WeatherQuery.Hourly.Builder with specific time interval:

val destinationPoint: Point = Point.fromLngLat(61.37, 55.15)
val routeDuration = route.directionsRoute.duration()
val arrivalTime = Date(Date().time + routeDuration.seconds.inWholeMilliseconds)
val arrivalTimeDelta = Date(time.time + 1.hours.inWholeMilliseconds)

val arrivalQuery = WeatherQuery.Hourly.Builder(destinationPoint)
.startTime(arrivalTime)
.endTime(arrivalTimeDelta)
.fields(
listOf(
Hourly.Fields.Temperature,
Hourly.Fields.PrecipitationProbability,
Hourly.Fields.PrecipitationType,
),
)
.build()
val conditions = weatherApi.getConditions(arrivalQuery).fold(
onSuccess = {
it.firstOrNull()?.conditions
},
onFailure = {
Log.e("Weather", it.message.orEmpty(), it)
null
},
)?.sortedBy { it.dateTime }

val arrivalTimeFields = conditions?.firstOrNull()?.fields
val temperature = arrivalTimeFields?.temperature
val precipitationProbability = arrivalTimeFields?.precipitationProbability
val precipitationType = arrivalTimeFields?.precipitationType
Log.d("Weather", "At arrival arrivalTime temperature will be: $temperature, chance of $precipitationType: $precipitationProbability")

Daily forecast

This data provides weather forecasts for up to 5 days ahead for the requested locations.

Even though getConditions returns a list of WeatherResult, the actual result includes only one item related to the provided location.

The WeatherResult contains a list of WeatherCondition instances, where each item represents the predicted weather at a day. If no interval is specified, the result includes 5 items, each corresponding to one of the next 5 days. The forecasted day can be determined using WeatherCondition.dateTime.

The code snippet below demonstrates how to get forecasted conditions for the next 5 days:

val location: Point = Point.fromLngLat(61.37, 55.15)
// Setting up all available fields to demonstrate all possible values.
// You can use only those that are necessary for your use case
val dailyQuery = WeatherQuery.Daily.Builder(location)
.fields(
listOf(
Daily.Fields.TemperatureMin,
Daily.Fields.TemperatureMax,
),
)
.build()
val fields = weatherApi.getConditions(dailyQuery).fold(
onSuccess = {
it.firstOrNull()?.conditions
},
onFailure = {
Log.e("Weather", it.message.orEmpty(), it)
null
},
)
?.sortedBy { it.dateTime }
?.map { it.fields }

val forecast = fields?.joinToString("\n") { "H: ${it.temperatureMax}, L: ${it.temperatureMin}" }
Log.d("Weather", forecast.orEmpty())

Route-based forecast

This data provides forecasted weather conditions and warnings along a NavigationRoute, corresponding to the estimated time a user will reach each point along the route.

In this case, the getConditions method may return multiple WeatherResult objects. Each result represents a specific location on the route and includes a single associated WeatherCondition. The dateTime field of the condition indicates when the forecast is applicable for that location.

This type of forecast is useful for displaying expected weather conditions during the user’s trip and for alerting them to potentially severe weather along the route.

To get warnings it is necessary to request routes with specific RouteOptions.annotationsList. At a minimum DirectionsCriteria.ANNOTATION_DURATION is necessary in that list.

val route: NavigationRoute = getNavigationRoute()
val weatherAlongRoute = WeatherQuery.WarningsAlongRoute.Builder(route)
.fields(
listOf(WarningsAlongRoute.Fields.WeatherPhrase),
)
.build()
val fields = weatherApi.getConditions(weatherAlongRoute).fold(
onSuccess = {
it
},
onFailure = {
Log.e("Weather", it.message.orEmpty(), it)
null
},
)

val warningsAtTime = results?.mapNotNull {
val condition = it.conditions.firstOrNull()
condition?.warning?.let { warning ->
Triple(warning, condition.dateTime, condition.fields.weatherPhrase)
}
}

val warningsAlongRouteText = warningsAtTime?.joinToString { (warning, dateTime , weatherPhrase) ->
"$warning at $dateTime, $weatherPhrase"
}.orEmpty()

Log.d("Weather", warningsAlongRouteText)
この{Type}は役に立ちましたか?