استخدام واجهات برمجة تطبيقات الأماكن والترميز الجغرافي مع التصميم المستند إلى البيانات للحدود

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

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

إضافة الأماكن والترميز الجغرافي إلى تطبيقات واجهة برمجة تطبيقات JavaScript للخرائط في الطرق التالية:

استخدام Places API

استخدام البحث النصي (جديد) للبحث عن منطقة

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

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

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();

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

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

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

الحصول على تفاصيل مكان معيّن

يمكن أن تكون بيانات تفاصيل المكان حول منطقة مفيدة جدًا. على سبيل المثال، يمكنك إجراء ما يلي:

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

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

تستدعي الدالة المثال التالي fetchFields() للحصول على تفاصيل المكان. بما في ذلك place.geometry.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 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، أو المنطقة، أو الرمز البريدي.
  • استخدم الترميز الجغرافي العكسي للعثور على معرفات الأماكن حسب إحداثيات خط العرض/خط الطول، أو معرفات الأماكن لجميع المكونات في موقع معين.

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

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

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

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

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

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