🔍

Location Service で近くの施設 (コンビニ、レストランなど) を検索する

に公開

Location Service で近くのコンビニやレストランを検索したい!

住宅の物件を検討する際に、近くのコンビニやレストラン、病院、学校などを検索して便利な立地なのか確かめるユースケースで Amazon Location Service が便利に活用できたりします。Location Service の一つの機能を挙げると、例えばこんなことができます

Location Service を使って Python のプログラムから、近くのコンビニやレストランを検索してみましょう。

実行例

うちのオフィスの住所を指定してみたときの例です。日本の情報もきちんと Location Service が返してくれています。以下の情報が見えます。住みやすい物件かどうかを、プログラムで自動的に情報収集して、LLM にわたしてある程度自動評価もしやすそうですね。

  • 店舗名、住所、直線距離、徒歩距離、徒歩で歩いた時の時間
> python3 search_nearby_restaurants.py
住所: 東京都品川区上大崎3丁目1−1 目黒セントラルスクエア
==================================================
座標: 経度=139.71652, 緯度=35.63337
==================================================
近くの飲食店を検索中...

見つかった飲食店: 10 件

[1] 割烹 酒場 銀座 ツルカメ 目黒店
    住所: 〒141-0021 東京都品川区上大崎3丁目1-1 割烹 酒場 銀座 ツルカメ 目黒店
    直線距離: 64 m
    徒歩距離: 250 m
    徒歩時間: 4分
    カテゴリ: レストラン

[2] yuuan
    住所: 〒141-0021 東京都品川区上大崎3丁目1-1 yuuan
    直線距離: 64 m
    徒歩距離: 250 m
    徒歩時間: 4分
    カテゴリ: レストラン

[3] To The Herbs
    住所: 〒141-0021 東京都品川区上大崎3丁目1-1 To The Herbs
    直線距離: 64 m
    徒歩距離: 250 m
    徒歩時間: 4分
    カテゴリ: レストラン
    料理タイプ: イタリア料理

[4] 鉄板ステーキ&ワイン En 目黒セントラルスクエア店
    住所: 〒141-0021 東京都品川区上大崎3丁目1-1 鉄板ステーキ&ワイン En 目黒セントラルスクエア店
    直線距離: 64 m
    徒歩距離: 250 m
    徒歩時間: 4分
    カテゴリ: レストラン
    料理タイプ: ステーキハウス

[5] ボスケ
    住所: 〒141-0021 東京都品川区上大崎3丁目1-1 ボスケ
    直線距離: 64 m
    徒歩距離: 250 m
    徒歩時間: 4分
    カテゴリ: レストラン

[6] バルマルシェコダマ ステーキ&ロブスター アトレ目黒店
    住所: 〒141-0021 東京都品川区上大崎3丁目1-1 バルマルシェコダマ ステーキ&ロブスター アトレ目黒店
    直線距離: 64 m
    徒歩距離: 268 m
    徒歩時間: 4分
    カテゴリ: バー、パブ、居酒屋, レストラン

[7] 回し寿司 活 活美登利 目黒店
    住所: 〒141-0021 東京都品川区上大崎3丁目1-1 回し寿司 活 活美登利 目黒店
    直線距離: 66 m
    徒歩距離: 271 m
    徒歩時間: 5分
    カテゴリ: レストラン
    料理タイプ: 日本料理-寿司, アジア料理, 日本料理, シーフード

[8] 林屋茶園 目黒セントラルスクエア店
    住所: 〒141-0021 東京都品川区上大崎3丁目1-1 林屋茶園 目黒セントラルスクエア店
    直線距離: 66 m
    徒歩距離: 65 m
    徒歩時間: 1分
    カテゴリ: コーヒー店, レストラン

[9] こめの家 目黒店
    住所: 〒141-0021 東京都品川区上大崎2丁目15-14 こめの家 目黒店
    直線距離: 76 m
    徒歩距離: 128 m
    徒歩時間: 2分
    カテゴリ: バー、パブ、居酒屋, レストラン
    料理タイプ: 日本料理

[10] ふぐ懐石料理 九重
    住所: 〒141-0021 東京都品川区上大崎2丁目15-15 ふぐ懐石料理 九重
    直線距離: 76 m
    徒歩距離: 143 m
    徒歩時間: 2分
    カテゴリ: レストラン
    料理タイプ: 日本料理, シーフード

==================================================
近くのコンビニを検索中...

見つかったコンビニ: 10 件

[1] 目黒セントラルスクエア
    住所: 〒141-0021 東京都品川区上大崎3丁目1-1 目黒セントラルスクエア
    直線距離: 0 m
    徒歩距離: 0 m
    徒歩時間: 1分未満

[2] ファミリーマートアトレ目黒店
    住所: 〒141-0021 東京都品川区上大崎3丁目1-1 ファミリーマートアトレ目黒店
    直線距離: 72 m
    徒歩距離: 151 m
    徒歩時間: 3分

[3] ファミリーマート目黒駅東口店
    住所: 〒141-0021 東京都品川区上大崎2丁目14-9 ファミリーマート目黒駅東口店
    直線距離: 87 m
    徒歩距離: 145 m
    徒歩時間: 2分

[4] NewDays ミニ 目黒2号
    住所: 〒141-0021 東京都品川区上大崎2丁目16-9 NewDays ミニ 目黒2号
    直線距離: 105 m
    徒歩距離: 189 m
    徒歩時間: 3分

[5] ファミリーマート目黒駅東店
    住所: 〒141-0021 東京都品川区上大崎2丁目12-2 ファミリーマート目黒駅東店
    直線距離: 174 m
    徒歩距離: 223 m
    徒歩時間: 4分

[6] ファミリーマート上大崎三丁目店
    住所: 〒141-0021 東京都品川区上大崎3丁目4-1 ファミリーマート上大崎三丁目店
    直線距離: 215 m
    徒歩距離: 269 m
    徒歩時間: 5分

[7] ファミリーマート目黒駅北店
    住所: 〒141-0021 東京都品川区上大崎2丁目17-2 ファミリーマート目黒駅北店
    直線距離: 225 m
    徒歩距離: 259 m
    徒歩時間: 4分

[8] ナチュラルローソン シティコート目黒
    住所: 〒141-0021 東京都品川区上大崎2丁目10-33 ナチュラルローソン シティコート目黒
    直線距離: 230 m
    徒歩距離: 293 m
    徒歩時間: 5分

[9] ファミリーマートアルコスクエア店
    住所: 〒141-0021 東京都品川区上大崎4丁目5-10 ファミリーマートアルコスクエア店
    直線距離: 283 m
    徒歩距離: 483 m
    徒歩時間: 8分

[10] セブンイレブン下目黒1丁目店
    住所: 〒153-0064 東京都目黒区下目黒1丁目3-1 セブンイレブン下目黒1丁目店
    直線距離: 315 m
    徒歩距離: 327 m
    徒歩時間: 6分

近くの施設を検索する

実装における重要なところを抜粋しています。まず、検索対象にする住所は、通常のテキストから扱えます。ただ、緯度経度に変換が必要で、テキストから緯度経度に変換する geocode API を Location Service で提供しています。

def geocode_address(client, address: str) -> Optional[Tuple[float, float]]:
    """
    住所を緯度・経度に変換する(ジオコーディング)

    Args:
        client: geo-places クライアント
        address: 検索する住所

    Returns:
        (経度, 緯度) のタプル、見つからない場合は None
    """
    response = client.geocode(
        QueryText=address,
        MaxResults=1,
        Language="ja"
    )

def main():
    region = "ap-northeast-1"
    places_client = boto3.client("geo-places", region_name=region)
    routes_client = boto3.client("geo-routes", region_name=region)

    # 検索する住所
    address = "東京都品川区上大崎3丁目1−1 目黒セントラルスクエア"

    # 1. 住所を座標に変換
    coordinates = geocode_address(places_client, address)

取得した緯度経度の情報を基に、search_nearby API で、近くの施設などを検索できます。

  • categories : 検索対象のカテゴリを指定します。例えば、コンビニなら convenience_store と指定します。指定可能なカテゴリは、ここの Document に記載されています。
  • radius_meters : 検索対象の施設の距離を指定します。
def search_nearby_places(
    client,
    longitude: float,
    latitude: float,
    categories: List[str],
    radius_meters: int = 1000
) -> List[Dict]:
    """
    指定した座標の近くにある施設を検索する

    Args:
        client: geo-places クライアント
        longitude: 経度
        latitude: 緯度
        categories: 検索するカテゴリのリスト(例: ["restaurant"], ["convenience_store"])
        radius_meters: 検索半径(メートル)

    Returns:
        施設情報のリスト
    """
    response = client.search_nearby(
        QueryPosition=[longitude, latitude],
        QueryRadius=radius_meters,
        Filter={
            "IncludeCategories": categories
        },
        MaxResults=10,
        Language="ja"
    )

移動距離を算出する

search_nearby API は直線距離を出してくれるのですが、やっぱり歩くときの実際の移動距離や時間がきになります。その際には、calculate_routes API が利用できます。移動する元と先の緯度経度を指定することで、その間の実際の道順に基づく距離や時間が得られます。

TravelMode="Pedestrian" と指定することで、移動手段は徒歩と指定をしています。他にも、車、トラックなどの移動手段も指定可能です。

def get_walking_route(
    routes_client,
    origin: Tuple[float, float],
    destination: Tuple[float, float]
) -> Optional[Dict]:
    """
    2点間の徒歩ルートを計算する

    Args:
        routes_client: geo-routes クライアント
        origin: 出発地点 (経度, 緯度)
        destination: 目的地点 (経度, 緯度)

    Returns:
        徒歩距離(メートル)と所要時間(秒)を含む辞書、エラー時は None
    """
    try:
        response = routes_client.calculate_routes(
            Origin=list(origin),
            Destination=list(destination),
            TravelMode="Pedestrian"
        )

料金について

https://aws.amazon.com/location/pricing/?nc1=h_ls

色々な料金の考え方があるのですが、住所から緯度経度へ変換する回数、近くの施設を検索する回数によって料金が発生します。1000 回のリクエストあたり、Core の場合は $0.5 となります。為替にもよりますが、1000 回実行あたり、約 75 円でしょうか。

image-20251221210538074

まとめ

Location Service を利用することで、指定した住所の近くの場所や施設を検索することができました。ぜひみなさんも Location Service でいろいろ触ってみてください!

付録 : サンプルコード全文

動作する Python コードの全文がこちらです。いろいろ実装変更してみて楽しんでみてください。

"""
AWS Location Service を使って住所近くの飲食店を検索する
"""

from typing import List, Dict, Optional, Tuple

import boto3


def get_walking_route(
    routes_client,
    origin: Tuple[float, float],
    destination: Tuple[float, float]
) -> Optional[Dict]:
    """
    2点間の徒歩ルートを計算する

    Args:
        routes_client: geo-routes クライアント
        origin: 出発地点 (経度, 緯度)
        destination: 目的地点 (経度, 緯度)

    Returns:
        徒歩距離(メートル)と所要時間(秒)を含む辞書、エラー時は None
    """
    try:
        response = routes_client.calculate_routes(
            Origin=list(origin),
            Destination=list(destination),
            TravelMode="Pedestrian"
        )

        if response.get("Routes"):
            route = response["Routes"][0]
            summary = route.get("Summary", {})
            return {
                "distance_meters": summary.get("Distance", 0),
                "duration_seconds": summary.get("Duration", 0)
            }
    except Exception as e:
        print(f"    ルート計算エラー: {e}")
    return None


def format_duration(seconds: int) -> str:
    """秒を「○分」形式に変換する"""
    minutes = round(seconds / 60)
    if minutes < 1:
        return "1分未満"
    return f"{minutes}分"


def geocode_address(client, address: str) -> Optional[Tuple[float, float]]:
    """
    住所を緯度・経度に変換する(ジオコーディング)

    Args:
        client: geo-places クライアント
        address: 検索する住所

    Returns:
        (経度, 緯度) のタプル、見つからない場合は None
    """
    response = client.geocode(
        QueryText=address,
        MaxResults=1,
        Language="ja"
    )

    if response.get("ResultItems"):
        position = response["ResultItems"][0]["Position"]
        # Position は [経度, 緯度] の形式
        return position[0], position[1]
    return None


def search_nearby_places(
    client,
    longitude: float,
    latitude: float,
    categories: List[str],
    radius_meters: int = 1000
) -> List[Dict]:
    """
    指定した座標の近くにある施設を検索する

    Args:
        client: geo-places クライアント
        longitude: 経度
        latitude: 緯度
        categories: 検索するカテゴリのリスト(例: ["restaurant"], ["convenience_store"])
        radius_meters: 検索半径(メートル)

    Returns:
        施設情報のリスト
    """
    response = client.search_nearby(
        QueryPosition=[longitude, latitude],
        QueryRadius=radius_meters,
        Filter={
            "IncludeCategories": categories
        },
        MaxResults=10,
        Language="ja"
    )

    places = []
    for item in response.get("ResultItems", []):
        # 施設の座標を取得
        position = item.get("Position", [])
        place = {
            "name": item.get("Title", "不明"),
            "address": item.get("Address", {}).get("Label", "住所不明"),
            "distance_meters": item.get("Distance", 0),
            "position": (position[0], position[1]) if len(position) >= 2 else None,
            "categories": [cat.get("LocalizedName", cat.get("Name", ""))
                          for cat in item.get("Categories", [])],
            "food_types": [food.get("LocalizedName", food.get("Id", ""))
                          for food in item.get("FoodTypes", [])]
        }
        places.append(place)

    return places


def main():
    # クライアントを作成
    # リージョンは利用可能なリージョンを指定(例: ap-northeast-1)
    region = "ap-northeast-1"
    places_client = boto3.client("geo-places", region_name=region)
    routes_client = boto3.client("geo-routes", region_name=region)

    # 検索する住所
    address = "東京都品川区上大崎3丁目1−1 目黒セントラルスクエア"

    print(f"住所: {address}")
    print("=" * 50)

    # 1. 住所を座標に変換
    coordinates = geocode_address(places_client, address)

    if coordinates is None:
        print("住所が見つかりませんでした。")
        return

    longitude, latitude = coordinates
    print(f"座標: 経度={longitude}, 緯度={latitude}")
    print("=" * 50)

    # 出発地点
    origin = (longitude, latitude)

    # 2. 近くの飲食店を検索
    # 指定できるカテゴリ : https://docs.aws.amazon.com/location/latest/developerguide/places-filtering.html#place-categories
    print("近くの飲食店を検索中...")
    restaurants = search_nearby_places(places_client, longitude, latitude, categories=["restaurant"], radius_meters=500)

    if not restaurants:
        print("飲食店が見つかりませんでした。")
    else:
        print(f"\n見つかった飲食店: {len(restaurants)} 件\n")
        for i, place in enumerate(restaurants, 1):
            print(f"[{i}] {place['name']}")
            print(f"    住所: {place['address']}")
            print(f"    直線距離: {place['distance_meters']} m")

            # 徒歩ルートを計算
            if place['position']:
                route = get_walking_route(routes_client, origin, place['position'])
                if route:
                    print(f"    徒歩距離: {route['distance_meters']} m")
                    print(f"    徒歩時間: {format_duration(route['duration_seconds'])}")

            if place['categories']:
                print(f"    カテゴリ: {', '.join(place['categories'])}")
            if place['food_types']:
                print(f"    料理タイプ: {', '.join(place['food_types'])}")
            print()

    # 3. 近くのコンビニを検索
    # 指定できるカテゴリ : https://docs.aws.amazon.com/location/latest/developerguide/places-filtering.html#place-categories
    print("=" * 50)
    print("近くのコンビニを検索中...")
    convenience_stores = search_nearby_places(places_client, longitude, latitude, categories=["convenience_store"], radius_meters=500)

    if not convenience_stores:
        print("コンビニが見つかりませんでした。")
    else:
        print(f"\n見つかったコンビニ: {len(convenience_stores)} 件\n")
        for i, place in enumerate(convenience_stores, 1):
            print(f"[{i}] {place['name']}")
            print(f"    住所: {place['address']}")
            print(f"    直線距離: {place['distance_meters']} m")

            # 徒歩ルートを計算
            if place['position']:
                route = get_walking_route(routes_client, origin, place['position'])
                if route:
                    print(f"    徒歩距離: {route['distance_meters']} m")
                    print(f"    徒歩時間: {format_duration(route['duration_seconds'])}")
            print()


if __name__ == "__main__":
    main()

アマゾン ウェブ サービス ジャパン (有志)

Discussion