境界線用データドリブン スタイル設定で Places API 群とジオコーディングを利用する

プラットフォームを選択: iOS JavaScript

Maps JavaScript API で Places API と Geocoding API を使用すると、地域を検索したり、場所の詳しい情報を取得したりすることができます。Geocoding API と Places API は、プレイス ID を取得できる便利で安定性の高いツールです。すでにプレイス ID を使用している場合、それらの ID を境界線用データドリブン スタイル設定に流用するのも簡単です。

Places API と Geocoding API は、次の方法で Maps JavaScript API アプリに組み込むことができます。

Places API を使用する

テキスト検索(新版)を使って地域を検索する

テキスト検索(新版)では、返すべき地域のタイプincludedType で指定することにより、地域データを含むプレイス ID を取得できます。テキスト検索(新版)API を使ってプレイス ID をリクエストしても、料金は発生しません。詳細

このサンプル地図では、searchByText リクエストを実行してカリフォルニア州トリニダード市のプレイス ID を取得し、境界線にスタイル設定を適用しています。

TypeScript

async function findBoundary() {
    const request = {
        query: 'Trinidad, CA',
        fields: ['id', 'location'],
        includedType: 'locality',
        locationBias: center,
    };

    const { Place } = await google.maps.importLibrary("places") as google.maps.PlacesLibrary;
    //@ts-ignore
    const { places } = await Place.searchByText(request);

    if (places.length) {
        const place = places[0];
        styleBoundary(place.id);
        map.setCenter(place.location);
    } else {
        console.log('No results');
    }
}

function styleBoundary(placeid) {
    // Define a style of transparent purple with opaque stroke.
    const styleFill = {
        strokeColor: '#810FCB',
        strokeOpacity: 1.0,
        strokeWeight: 3.0,
        fillColor: '#810FCB',
        fillOpacity: 0.5
    };

    // Define the feature style function.
    featureLayer.style = (params) => {
        if (params.feature.placeId == placeid) {
            return styleFill;
        }
    };
}

JavaScript

async function findBoundary() {
  const request = {
    query: "Trinidad, CA",
    fields: ["id", "location"],
    includedType: "locality",
    locationBias: center,
  };
  const { Place } = await google.maps.importLibrary("places");
  //@ts-ignore
  const { places } = await Place.searchByText(request);

  if (places.length) {
    const place = places[0];

    styleBoundary(place.id);
    map.setCenter(place.location);
  } else {
    console.log("No results");
  }
}

function styleBoundary(placeid) {
  // Define a style of transparent purple with opaque stroke.
  const styleFill = {
    strokeColor: "#810FCB",
    strokeOpacity: 1.0,
    strokeWeight: 3.0,
    fillColor: "#810FCB",
    fillOpacity: 0.5,
  };

  // Define the feature style function.
  featureLayer.style = (params) => {
    if (params.feature.placeId == placeid) {
      return styleFill;
    }
  };
}

サンプル ソースコードの全文を見る

TypeScript

let map;
let featureLayer;
let center;

async function initMap() {
    const { Map } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary;

    center = {lat: 41.059, lng: -124.151}; // Trinidad, CA

    map = new Map(document.getElementById('map') as HTMLElement, {
        center: center,
        zoom: 15,
        // In the cloud console, configure this Map ID with a style that enables the
        // "Locality" Data Driven Styling type.
        mapId: 'a3efe1c035bad51b', // <YOUR_MAP_ID_HERE>,
    });

    featureLayer = map.getFeatureLayer('LOCALITY');

    findBoundary();
}
async function findBoundary() {
    const request = {
        query: 'Trinidad, CA',
        fields: ['id', 'location'],
        includedType: 'locality',
        locationBias: center,
    };

    const { Place } = await google.maps.importLibrary("places") as google.maps.PlacesLibrary;
    //@ts-ignore
    const { places } = await Place.searchByText(request);

    if (places.length) {
        const place = places[0];
        styleBoundary(place.id);
        map.setCenter(place.location);
    } else {
        console.log('No results');
    }
}

function styleBoundary(placeid) {
    // Define a style of transparent purple with opaque stroke.
    const styleFill = {
        strokeColor: '#810FCB',
        strokeOpacity: 1.0,
        strokeWeight: 3.0,
        fillColor: '#810FCB',
        fillOpacity: 0.5
    };

    // Define the feature style function.
    featureLayer.style = (params) => {
        if (params.feature.placeId == placeid) {
            return styleFill;
        }
    };
}
initMap();

JavaScript

let map;
let featureLayer;
let center;

async function initMap() {
  const { Map } = await google.maps.importLibrary("maps");

  center = { lat: 41.059, lng: -124.151 }; // Trinidad, CA
  map = new Map(document.getElementById("map"), {
    center: center,
    zoom: 15,
    // In the cloud console, configure this Map ID with a style that enables the
    // "Locality" Data Driven Styling type.
    mapId: "a3efe1c035bad51b", // <YOUR_MAP_ID_HERE>,
  });
  featureLayer = map.getFeatureLayer("LOCALITY");
  findBoundary();
}

async function findBoundary() {
  const request = {
    query: "Trinidad, CA",
    fields: ["id", "location"],
    includedType: "locality",
    locationBias: center,
  };
  const { Place } = await google.maps.importLibrary("places");
  //@ts-ignore
  const { places } = await Place.searchByText(request);

  if (places.length) {
    const place = places[0];

    styleBoundary(place.id);
    map.setCenter(place.location);
  } else {
    console.log("No results");
  }
}

function styleBoundary(placeid) {
  // Define a style of transparent purple with opaque stroke.
  const styleFill = {
    strokeColor: "#810FCB",
    strokeOpacity: 1.0,
    strokeWeight: 3.0,
    fillColor: "#810FCB",
    fillOpacity: 0.5,
  };

  // Define the feature style function.
  featureLayer.style = (params) => {
    if (params.feature.placeId == placeid) {
      return styleFill;
    }
  };
}

initMap();

Places Autocomplete を使用して地域を検索する

Places Autocomplete ウィジェットを使用すると、ユーザーが地域を簡単に検索できるようになります。地域のみを返すように Places Autocomplete ウィジェットを設定するには、次のスニペットに示すように types(regions) に設定します。

// Set up the Autocomplete widget to return only region results.
const autocompleteOptions = {
  fields: ["place_id", "type"],
  strictBounds: false,
  types: ["(regions)"],
};

地域の Place Details を取得する

地域の Place Details データは、非常に便利です。たとえば、次のことができます。

  • 地名に基づいて境界線のプレイス ID を検索する。
  • 境界線にズームするビューポートを取得する。
  • 境界線の対象物タイプ(locality など)を取得する。
  • フォーマット済みの住所を取得する。米国であれば「地名、州、国」に変換されます(例: 「Ottumwa, IA, USA」)。
  • 写真など、その他の便利なデータを取得する。

次のサンプル関数を使用すると、カリフォルニア州トリニダード市の境界線を求め、その結果に地図の中心を合わせます。

次のサンプル関数では、fetchFields() を呼び出して place.geometry.viewport を含む Place Details を取得した後、map.fitBounds() を呼び出して、選択された境界線ポリゴンを基準に地図をセンタリングしています。

    async function getPlaceDetails(placeId) {
        // Use place ID to create a new Place instance.
        const place = new google.maps.places.Place({
            id: placeId,
        });

        // Call fetchFields, passing the desired data fields.
        await place.fetchFields({ fields: ['displayName', 'formattedAddress', 'geometry', 'type'] });

        // Zoom to the boundary polygon.
        let viewport = place.geometry.viewport;
        map.fitBounds(viewport, 155);

        // Print some place details to the console.
        const types = place.types;
        console.log("Feature type: " + types[0]);
        console.log("Formatted address: " + place.formattedAddress);
    }

Geocoding API を使用する

Geocoding API を使用すると、住所を地理座標に変換できます。また、その逆も同様です。次のような使用方法は、境界線用データドリブン スタイル設定との組み合わせに最適です。

  • ジオコーディングを使用して地域のビューポートを取得する。
  • ジオコーディングの呼び出しにコンポーネントのフィルタリングを適用して、行政区域 1~4、地域区分、または郵便番号のプレイス ID を取得する。
  • リバース ジオコーディングを使用して緯度と経度の座標でプレイス ID を取得する、または特定の場所にあるすべてのコンポーネントのプレイス ID を返す。

地域のビューポートを取得する

ジオコーディング サービスはプレイス ID を受け取ってビューポートを返すことができます。ビューポートを map.fitBounds() 関数に渡すことで、地図上の境界線ポリゴンにズームできます。次の例では、ジオコーディング サービスを使用してビューポートを取得し、map.fitBounds() を呼び出しています。

// Set up the geocoder.
geocoder = new google.maps.Geocoder();

...

// Call Geocoding API and zoom to the resulting bounds.
function zoomToPolygon(placeid) {
    geocoder
        .geocode({ placeId: placeid })
        .then(({ results }) => {
            map.fitBounds(results[0].geometry.viewport, 155);
        })
        .catch((e) => {
            console.log('Geocoder failed due to: ' + e)
        });
}

リバース ジオコーディングを使用する

リバース ジオコーディングを使用すると、プレイス ID を取得できます。以下の例のジオコーディング サービスの関数は、指定された緯度と経度の座標にあるすべての住所コンポーネントのプレイス ID を返します。

// Set up the geocoder.
geocoder = new google.maps.Geocoder();

...

// Call Geocoding API.
function getPlaceIds(latLng) {
    geocoder
        .geocode({ latLng })
        .then(({ results }) => {
            console.log('Geocoding result:');
            console.log(results[0]);
            console.log(results[0].place_id);
            console.log(results[0].address_components);
        })
        .catch((e) => {
            console.log('Geocoder failed due to: ' + e)
        });
}

同様のリバース ジオコーディングをウェブサービス呼び出しで行う場合、次のようになります。

https://maps.googleapis.com/maps/api/geocode/json?key="YOUR_API_KEY"&latlng=41.864182,-87.676930

コンポーネント フィルタリングでリバース ジオコーディングを使用して、指定された場所で以下の 1 つ以上のタイプの住所コンポーネントを取得します。

  • administrativeArea
  • country
  • locality
  • postalCode

次の例の関数では、ジオコーディング サービスを使用し、リバース ジオコーディングでコンポーネントの制限を追加して、指定された場所の locality タイプの住所コンポーネントのみをすべて取得します。

// Set up the geocoder.
geocoder = new google.maps.Geocoder();

...

function getPlaceIdWithRestrictions(latLng) {
    geocoder
        .geocode({ latLng,
            componentRestrictions: {
              country: "US",
              locality: "chicago",
            },
        })
        .then(({ results }) => {
            console.log('Geocoding result with restriction:');
            console.log(results[0]);
            console.log(results[0].place_id);
            console.log(results[0].address_components);
            console.log(results[0].address_components[1].types[0]);
            console.log(results[0].address_components[1].long_name);
        })
        .catch((e) => {
            console.log('getPlaceId Geocoder failed due to: ' + e)
        });
}

同様のリバース ジオコーディングをウェブサービス呼び出しで行う場合、次のようになります。

https://maps.googleapis.com/maps/api/geocode/json?key="YOUR_API_KEY"&latlng=41.864182,-87.676930&result_type=locality