استخدام Places APIs وGeocoding مع تنسيق مستند إلى البيانات للحدود

اختيار النظام الأساسي: Android‏ iOS‏ JavaScript‏

المطوّرون في المنطقة الاقتصادية الأوروبية

يمكنك استخدام Places API وGeocoding API في Maps JavaScript API للبحث عن المناطق والحصول على مزيد من المعلومات عن الأماكن. تُعدّ Geocoding API وPlaces API بديلَين فعّالَين ومستقرَّين للحصول على أرقام تعريف الأماكن. إذا كنت تستخدم أرقام تعريف الأماكن حاليًا، يمكنك إعادة استخدامها بسهولة مع ميزة "التصميم المستند إلى البيانات" للحدود.

يمكنك إضافة Places وGeocoding إلى تطبيقات Maps JavaScript API بالطرق التالية:

استخدام Places API

يمكنك استخدام "البحث النصي" (الجديد) للحصول على رقم تعريف مكان يتضمّن بيانات المنطقة باستخدام includedType لتحديد نوع المنطقة التي تريد عرضها. لن يتم تحصيل أي رسوم مقابل استخدام Text Search (New) API لطلب أرقام تعريف الأماكن فقط. مزيد من المعلومات

يوضّح مثال الخريطة هذا كيفية إرسال طلب searchByText للحصول على رقم تعريف المكان لمدينة ترينيداد في كاليفورنيا، ثم تطبيق النمط على الحدود:

TypeScript

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

    const { Place } = await google.maps.importLibrary('places');
    const { places } = await Place.searchByText(request);

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

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

    // Define the feature style function.
    featureLayer.style = (params: google.maps.FeatureStyleFunctionOptions) => {
        const placeFeature = params.feature as google.maps.PlaceFeature;
        if (placeFeature.placeId === placeid) {
            return styleFill;
        }
        return null;
    };
}

JavaScript

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

    const { Place } = await google.maps.importLibrary('places');
    const { places } = await Place.searchByText(request);

    if (places.length) {
        const place = places[0];
        styleBoundary(place.id);
        innerMap.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) => {
        const placeFeature = params.feature;
        if (placeFeature.placeId === placeid) {
            return styleFill;
        }
        return null;
    };
}

الاطّلاع على الرمز المصدر للمثال الكامل

TypeScript

let innerMap: google.maps.Map;
let featureLayer: google.maps.FeatureLayer;
let center: google.maps.LatLngLiteral;

async function init() {
    // Load the needed libraries.
    await google.maps.importLibrary('maps');

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

    // Get the gmp-map element.
    const mapElement = document.querySelector('gmp-map')!;

    // Get the inner map.
    innerMap = mapElement.innerMap;

    // Get the LOCALITY feature layer.
    featureLayer = innerMap.getFeatureLayer('LOCALITY');

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

    const { Place } = await google.maps.importLibrary('places');
    const { places } = await Place.searchByText(request);

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

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

    // Define the feature style function.
    featureLayer.style = (params: google.maps.FeatureStyleFunctionOptions) => {
        const placeFeature = params.feature as google.maps.PlaceFeature;
        if (placeFeature.placeId === placeid) {
            return styleFill;
        }
        return null;
    };
}
void init();

JavaScript

let innerMap;
let featureLayer;
let center;

async function init() {
    // Load the needed libraries.
    await google.maps.importLibrary('maps');

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

    // Get the gmp-map element.
    const mapElement = document.querySelector('gmp-map');

    // Get the inner map.
    innerMap = mapElement.innerMap;

    // Get the LOCALITY feature layer.
    featureLayer = innerMap.getFeatureLayer('LOCALITY');

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

    const { Place } = await google.maps.importLibrary('places');
    const { places } = await Place.searchByText(request);

    if (places.length) {
        const place = places[0];
        styleBoundary(place.id);
        innerMap.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) => {
        const placeFeature = params.feature;
        if (placeFeature.placeId === placeid) {
            return styleFill;
        }
        return null;
    };
}
void init();

استخدام ميزة "الإكمال التلقائي للأماكن" للعثور على المناطق

توفّر أداة "الإكمال التلقائي للمكان" طريقة ملائمة تتيح للمستخدمين البحث عن المناطق. لضبط أداة "الإكمال التلقائي للأماكن" لعرض المناطق فقط، اضبط includedPrimaryTypes على (regions)، كما هو موضّح في المقتطف التالي:

// Set up the Autocomplete widget to return only region results.
placeAutocomplete = document.querySelector(
    'gmp-place-autocomplete'
) as google.maps.places.PlaceAutocompleteElement;
placeAutocomplete.includedPrimaryTypes = ['(regions)'];

الحصول على تفاصيل الأماكن في منطقة معيّنة

يمكن أن تكون بيانات تفاصيل المكان لمنطقة معيّنة مفيدة للغاية. يمكنك مثلاً:

  • ابحث عن أرقام تعريف الأماكن الحدودية استنادًا إلى أسماء الأماكن.
  • الحصول على إطار العرض للتكبير إلى حدود معيّنة
  • الحصول على نوع الميزة للحدود (على سبيل المثال locality)
  • احصل على العنوان المنسَّق الذي يتم تحليله إلى "اسم المكان، الولاية، البلد" في منطقة الولايات المتحدة (على سبيل المثال، "أوتوموا، آيوا، الولايات المتحدة الأمريكية").
  • الحصول على بيانات مفيدة أخرى، مثل مراجعات المستخدمين وصورهم

تعثر الدالة في المثال التالي على حدود مدينة ترينيداد في كاليفورنيا، وتوسّط الخريطة على النتيجة:

يستدعي المثال التالي الدالة fetchFields() للحصول على تفاصيل المكان، بما في ذلك place.viewport، ثم يستدعي الدالة 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 data fields you want.
        await place.fetchFields({ fields: ['displayName', 'formattedAddress', 'viewport', 'types'] });

        // Zoom to the boundary polygon.
        let viewport = place.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 تحويل العناوين إلى إحداثيات جغرافية والعكس. تتوافق الاستخدامات التالية بشكل جيد مع ميزة "التصميم المستند إلى البيانات" للحدود:

  • استخدِم Geocoding API للحصول على إطار العرض لمنطقة معيّنة.
  • يمكنك تطبيق فلترة المكوّنات على طلب الترميز الجغرافي للحصول على أرقام تعريف الأماكن للمناطق الإدارية من 1 إلى 4 أو المنطقة أو الرمز البريدي.
  • استخدِم عكس الترميز الجغرافي للعثور على أرقام تعريف الأماكن حسب إحداثيات خطوط العرض/الطول، أو حتى عرض أرقام تعريف الأماكن لجميع المكوّنات في موقع جغرافي معيّن.

الحصول على إطار العرض لمنطقة معيّنة

يمكن لخدمة الترميز الجغرافي استخدام رقم تعريف المكان وعرض إطار عرض، والذي يمكنك تمريره إلى دالة 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)
        });
}

استخدام عكس الترميز الجغرافي

يمكن استخدام عكس الترميز الجغرافي للعثور على أرقام تعريف الأماكن. يعرض مثال دالة خدمة الترميز الجغرافي التالي أرقام تعريف الأماكن لجميع مكوّنات العناوين في إحداثيات خطوط العرض/الطول المحدّدة:

// 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)
        });
}

في ما يلي طلب خدمة الويب المكافئ لعكس الترميز الجغرافي:

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

لاستخدام عكس الترميز الجغرافي مع فلترة المكوّنات للحصول على مكوّن العنوان لنوع واحد أو أكثر من الأنواع التالية في الموقع الجغرافي المحدّد:

  • 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)
        });
}

هذا هو طلب خدمة الويب المكافئ لعكس الترميز الجغرافي:

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