Aracılığıyla paylaş


Veri kaynağı oluşturma (Android SDK)

Azure Haritalar Android SDK'sı verileri veri kaynaklarında depolar. Veri kaynaklarının kullanılması, veri işlemlerini sorgulama ve işleme için en iyi duruma getirmektedir. Şu anda iki tür veri kaynağı vardır:

  • GeoJSON kaynağı: Ham konum verilerini GeoJSON biçiminde yerel olarak yönetir. Küçük ve orta ölçekli veri kümeleri (yüz binlerce şeklin yukarısı) için iyidir.
  • Vektör kutucuğu kaynağı: Geçerli harita görünümü için vektör kutucukları olarak biçimlendirilmiş verileri haritalar döşeme sistemine göre yükler. Büyük ve büyük veri kümeleri (milyonlarca veya milyarlarca şekil) için idealdir.

Not

Android SDK'sı kullanımdan kaldırılmasını Azure Haritalar

Android için Azure Haritalar Yerel SDK artık kullanım dışıdır ve 31/3/25 tarihinde kullanımdan kaldırılacaktır. Hizmet kesintilerini önlemek için 31.03.25'e kadar Azure Haritalar Web SDK'sına geçin. Daha fazla bilgi için bkz. Android SDK geçiş kılavuzu Azure Haritalar.

GeoJSON veri kaynağı

Azure Haritalar, birincil veri modellerinden biri olarak GeoJSON kullanır. GeoJSON, jeo-uzamsal verileri JSON biçiminde göstermek için açık bir jeo-uzamsal standart yoldur. GeoJSON verilerini kolayca oluşturmak ve seri hale getirmek için Azure Haritalar Android SDK'sında bulunan GeoJSON sınıfları. GeoJSON verilerini DataSource sınıfında yükleyip depolayıp katmanlar kullanarak işlenmelidir. Aşağıdaki kodda GeoJSON nesnelerinin Azure Haritalar'de nasıl oluşturulabileceği gösterilmektedir.

/*
    Raw GeoJSON feature

    {
         "type": "Feature",
         "geometry": {
             "type": "Point",
             "coordinates": [-100, 45]
         },
         "properties": {
             "custom-property": "value"
         }
    }

*/

//Create a point feature.
Feature feature = Feature.fromGeometry(Point.fromLngLat(-100, 45));

//Add a property to the feature.
feature.addStringProperty("custom-property", "value");

//Add the feature to the data source.
source.add(feature);
/*
    Raw GeoJSON feature

    {
         "type": "Feature",
         "geometry": {
             "type": "Point",
             "coordinates": [-100, 45]
         },
         "properties": {
             "custom-property": "value"
         }
    }

*/

//Create a point feature.
val feature = Feature.fromGeometry(Point.fromLngLat(-100, 45))

//Add a property to the feature.
feature.addStringProperty("custom-property", "value")

//Add the feature to the data source.
source.add(feature)

İpucu

GeoJSON verileri bir örneğe DataSource üç yöntemden biri kullanılarak eklenebilir: add, importDataFromUrlve setShapes. yöntemi, setShapes bir veri kaynağındaki tüm verilerin üzerine yazmak için etkili bir yol sağlar. Bir veri kaynağındaki clear tüm verileri değiştirmek için then add yöntemlerini çağırırsanız, haritaya iki işleme çağrısı yapılır. yöntemi verileri setShape temizler ve eşlemeye tek bir işleme çağrısıyla veri kaynağına ekler.

Alternatif olarak, aşağıdaki örnek kodda gösterildiği gibi, özellikler önce bir JsonObject'e yüklenebilir, ardından oluştururken özelliğe geçirilebilir.

//Create a JsonObject to store properties for the feature.
JsonObject properties = new JsonObject();
properties.addProperty("custom-property", "value");

Feature feature = Feature.fromGeometry(Point.fromLngLat(-100, 45), properties);
//Create a JsonObject to store properties for the feature.
val properties = JsonObject()
properties.addProperty("custom-property", "value")

val feature = Feature.fromGeometry(Point.fromLngLat(-100, 45), properties)

GeoJSON özelliği oluşturulduktan sonra haritanın özelliği aracılığıyla sources haritaya bir veri kaynağı eklenebilir. Aşağıdaki kod, bir öğesinin nasıl oluşturulacağını DataSource, haritaya nasıl ekleneceğini ve veri kaynağına bir özellik eklemeyi gösterir.

//Create a data source and add it to the map.
DataSource source = new DataSource();
map.sources.add(source);

//Add GeoJSON feature to the data source.
source.add(feature);

Aşağıdaki kodda GeoJSON Özelliği, FeatureCollection ve geometri oluşturmanın çeşitli yolları gösterilmektedir.

//GeoJSON Point Geometry
Point point = Point.fromLngLat(LONGITUDE, LATITUDE);

//GeoJSON Point Geometry
LineString linestring = LineString.fromLngLats(PointList);

//GeoJSON Polygon Geometry
Polygon polygon = Polygon.fromLngLats(listOfPointList);

Polygon polygonFromOuterInner = Polygon.fromOuterInner(outerLineStringObject,innerLineStringObject);

//GeoJSON MultiPoint Geometry
MultiPoint multiPoint = MultiPoint.fromLngLats(PointList);

//GeoJSON MultiLineString Geometry
MultiLineString multiLineStringFromLngLat = MultiLineString.fromLngLats(listOfPointList);

MultiLineString multiLineString = MultiLineString.fromLineString(singleLineString);

//GeoJSON MultiPolygon Geometry
MultiPolygon multiPolygon = MultiPolygon.fromLngLats(listOflistOfPointList);

MultiPolygon multiPolygonFromPolygon = MultiPolygon.fromPolygon(polygon);

MultiPolygon multiPolygonFromPolygons = MultiPolygon.fromPolygons(PolygonList);

//GeoJSON Feature
Feature pointFeature = Feature.fromGeometry(Point.fromLngLat(LONGITUDE, LATITUDE));

//GeoJSON FeatureCollection 
FeatureCollection featureCollectionFromSingleFeature = FeatureCollection.fromFeature(pointFeature);

FeatureCollection featureCollection = FeatureCollection.fromFeatures(listOfFeatures);
//GeoJSON Point Geometry
val point = Point.fromLngLat(LONGITUDE, LATITUDE)

//GeoJSON Point Geometry
val linestring = LineString.fromLngLats(PointList)

//GeoJSON Polygon Geometry
val polygon = Polygon.fromLngLats(listOfPointList)

val polygonFromOuterInner = Polygon.fromOuterInner(outerLineStringObject, innerLineStringObject)

//GeoJSON MultiPoint Geometry
val multiPoint = MultiPoint.fromLngLats(PointList)

//GeoJSON MultiLineString Geometry
val multiLineStringFromLngLat = MultiLineString.fromLngLats(listOfPointList)

val multiLineString = MultiLineString.fromLineString(singleLineString)

//GeoJSON MultiPolygon Geometry
val multiPolygon = MultiPolygon.fromLngLats(listOflistOfPointList)

val multiPolygonFromPolygon = MultiPolygon.fromPolygon(polygon)

val multiPolygonFromPolygons = MultiPolygon.fromPolygons(PolygonList)

//GeoJSON Feature
val pointFeature = Feature.fromGeometry(Point.fromLngLat(LONGITUDE, LATITUDE))

//GeoJSON FeatureCollection 
val featureCollectionFromSingleFeature = FeatureCollection.fromFeature(pointFeature)

val featureCollection = FeatureCollection.fromFeatures(listOfFeatures)

GeoJSON serileştirme ve seri durumdan çıkarma

Özellik koleksiyonu, özellik ve geometri sınıflarının tümü serileştirmeye yardımcı olan ve toJson() statik yöntemlere sahiptirfromJson(). yönteminden fromJson() geçirilen biçimlendirilmiş geçerli JSON Dizesi geometri nesnesini oluşturur. Bu fromJson() yöntem ayrıca Gson veya diğer serileştirme/seri durumdan çıkarma stratejilerini kullanabileceğiniz anlamına gelir. Aşağıdaki kod, dizeli bir GeoJSON özelliğinin nasıl alınıp Feature sınıfına seri durumdan çıkarılıp bir GeoJSON dizesine geri seri hale getirilmeyi gösterir.

//Take a stringified GeoJSON object.
String GeoJSON_STRING = "{"
    + "      \"type\": \"Feature\","            
    + "      \"geometry\": {"
    + "            \"type\": \"Point\""
    + "            \"coordinates\": [-100, 45]"
    + "      },"
    + "      \"properties\": {"
    + "            \"custom-property\": \"value\""
    + "      },"
    + "}";

//Deserialize the JSON string into a feature.
Feature feature = Feature.fromJson(GeoJSON_STRING);

//Serialize a feature collection to a string.
String featureString = feature.toJson();
//Take a stringified GeoJSON object.
val GeoJSON_STRING = ("{"
        + "      \"type\": \"Feature\","
        + "      \"geometry\": {"
        + "            \"type\": \"Point\""
        + "            \"coordinates\": [-100, 45]"
        + "      },"
        + "      \"properties\": {"
        + "            \"custom-property\": \"value\""
        + "      },"
        + "}")

//Deserialize the JSON string into a feature.
val feature = Feature.fromJson(GeoJSON_STRING)

//Serialize a feature collection to a string.
val featureString = feature.toJson()

Web veya assets klasöründen GeoJSON verilerini içeri aktarma

GeoJSON dosyalarının çoğu bir FeatureCollection içerir. GeoJSON dosyalarını dize olarak okuyun ve seri durumdan FeatureCollection.fromJson çıkarmak için yöntemini kullanın.

sınıfı, DataSource Web'deki veya varlık klasöründeki bir dosyanın URL'sini kullanarak GeoJSON dosyalarına yükleyebilen adlı importDataFromUrl yerleşik bir yönteme sahiptir. Bu yöntem , veri kaynağı haritaya eklenmeden önce çağrılmalıdır .

zone_pivot_groups: azure-maps-android

//Create a data source and add it to the map.
DataSource source = new DataSource();

//Import the geojson data and add it to the data source.
source.importDataFromUrl("URL_or_FilePath_to_GeoJSON_data");

//Examples:
//source.importDataFromUrl("asset://sample_file.json");
//source.importDataFromUrl("https://example.com/sample_file.json");

//Add data source to the map.
map.sources.add(source);
//Create a data source and add it to the map.
var source = new DataSource()

//Import the geojson data and add it to the data source.
source.importDataFromUrl("URL_or_FilePath_to_GeoJSON_data")

//Examples:
//source.importDataFromUrl("asset://sample_file.json")
//source.importDataFromUrl("https://example.com/sample_file.json")

//Add data source to the map.
map.sources.add(source)

importDataFromUrl yöntemi, bir GeoJSON akışını bir veri kaynağına yüklemek için kolay bir yol sağlar, ancak verilerin nasıl yüklendiği ve yüklendikten sonra ne olacağı konusunda sınırlı denetim sağlar. Aşağıdaki kod, web veya assets klasöründen verileri içeri aktarmak ve bir geri çağırma işlevi aracılığıyla ui iş parçacığına döndürmek için yeniden kullanılabilir bir sınıftır. Ardından, verileri işlemek, haritaya eklemek, sınırlayıcı kutusunu hesaplamak ve harita kamerasını güncelleştirmek için geri çağırmaya daha fazla yük sonrası mantığı ekleyin.

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.webkit.URLUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.net.ssl.HttpsURLConnection;

public class Utils {

    interface SimpleCallback {
        void notify(String result);
    }

    /**
     * Imports data from a web url or asset file name and returns it to a callback.
     * @param urlOrFileName A web url or asset file name that points to data to load.
     * @param context The context of the app.
     * @param callback The callback function to return the data to.
     */
    public static void importData(String urlOrFileName, Context context, SimpleCallback callback){
        importData(urlOrFileName, context, callback, null);
    }

    /**
     * Imports data from a web url or asset file name and returns it to a callback.
     * @param urlOrFileName A web url or asset file name that points to data to load.
     * @param context The context of the app.
     * @param callback The callback function to return the data to.
     * @param error A callback function to return errors to.
     */
    public static void importData(String urlOrFileName, Context context, SimpleCallback callback, SimpleCallback error){
        if(urlOrFileName != null && callback != null) {
            ExecutorService executor = Executors.newSingleThreadExecutor();
            Handler handler = new Handler(Looper.getMainLooper());

            executor.execute(() -> {
                String data = null;

                try {

                    if(URLUtil.isNetworkUrl(urlOrFileName)){
                        data = importFromWeb(urlOrFileName);
                    } else {
                        //Assume file is in assets folder.
                        data = importFromAssets(context, urlOrFileName);
                    }

                    final String result = data;

                    handler.post(() -> {
                        //Ensure the resulting data string is not null or empty.
                        if (result != null && !result.isEmpty()) {
                            callback.notify(result);
                        } else {
                            error.notify("No data imported.");
                        }
                    });
                } catch(Exception e) {
                    if(error != null){
                        error.notify(e.getMessage());
                    }
                }
            });
        }
    }

    /**
     * Imports data from an assets file as a string.
     * @param context The context of the app.
     * @param fileName The asset file name.
     * @return
     * @throws IOException
     */
    private static String importFromAssets(Context context, String fileName) throws IOException {
        InputStream stream = null;

        try {
            stream = context.getAssets().open(fileName);

            if(stream != null) {
                return readStreamAsString(stream);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // Close Stream and disconnect HTTPS connection.
            if (stream != null) {
                stream.close();
            }
        }

        return null;
    }

    /**
     * Imports data from the web as a string.
     * @param url URL to the data.
     * @return
     * @throws IOException
     */
    private static String importFromWeb(String url) throws IOException {
        InputStream stream = null;
        HttpsURLConnection connection = null;
        String result = null;

        try {
            connection = (HttpsURLConnection) new URL(url).openConnection();

            //For this use case, set HTTP method to GET.
            connection.setRequestMethod("GET");

            //Open communications link (network traffic occurs here).
            connection.connect();

            int responseCode = connection.getResponseCode();
            if (responseCode != HttpsURLConnection.HTTP_OK) {
                throw new IOException("HTTP error code: " + responseCode);
            }

            //Retrieve the response body as an InputStream.
            stream = connection.getInputStream();

            if (stream != null) {
                return readStreamAsString(stream);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // Close Stream and disconnect HTTPS connection.
            if (stream != null) {
                stream.close();
            }
            if (connection != null) {
                connection.disconnect();
            }
        }

        return result;
    }

    /**
     * Reads an input stream as a string.
     * @param stream Stream to convert.
     * @return
     * @throws IOException
     */
    private static String readStreamAsString(InputStream stream) throws IOException {
        //Convert the contents of an InputStream to a String.
        BufferedReader in = new BufferedReader(new InputStreamReader(stream, "UTF-8"));

        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }

        in.close();

        return response.toString();
    }
}
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.webkit.URLUtil
import java.net.URL
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

class Utils {
    companion object {

        /**
            * Imports data from a web url or asset file name and returns it to a callback.
            * @param urlOrFileName A web url or asset file name that points to data to load.
            * @param context The context of the app.
            * @param callback The callback function to return the data to.
            */
        fun importData(urlOrFileName: String?, context: Context, callback: (String?) -> Unit) {
            importData(urlOrFileName, context, callback, null)
        }

        /**
            * Imports data from a web url or asset file name and returns it to a callback.
            * @param urlOrFileName A web url or asset file name that points to data to load.
            * @param context The context of the app.
            * @param callback The callback function to return the data to.
            * @param error A callback function to return errors to.
            */
        public fun importData(urlOrFileName: String?, context: Context, callback: (String?) -> Unit, error: ((String?) -> Unit)?) {
            if (urlOrFileName != null && callback != null) {
                val executor: ExecutorService = Executors.newSingleThreadExecutor()
                val handler = Handler(Looper.getMainLooper())
                executor.execute {
                    var data: String? = null

                    try {
                        data = if (URLUtil.isNetworkUrl(urlOrFileName)) {
                            URL(urlOrFileName).readText()
                        } else { //Assume file is in assets folder.
                            context.assets.open(urlOrFileName).bufferedReader().use{
                                it.readText()
                            }
                        }

                        handler.post {
                            //Ensure the resulting data string is not null or empty.
                            if (data != null && !data.isEmpty()) {
                                callback(data)
                            } else {
                                error!!("No data imported.")
                            }
                        }
                    } catch (e: Exception) {
                        error!!(e.message)
                    }
                }
            }
        }
    }
}

Aşağıdaki kod, GeoJSON verilerini dize olarak içeri aktarmak ve bir geri çağırma yoluyla ui iş parçacığına döndürmek için bu yardımcı programın nasıl kullanılacağını gösterir. Geri çağırmada dize verileri bir GeoJSON Özellik koleksiyonunda seri hale getirilebilir ve veri kaynağına eklenebilir. İsteğe bağlı olarak haritalar kamerasını verilere odaklanacak şekilde güncelleştirin.

//Create a data source and add it to the map.
DataSource source = new DataSource();
map.sources.add(source);

//Import the geojson data and add it to the data source.
Utils.importData("URL_or_FilePath_to_GeoJSON_data",
    this,
    (String result) -> {
        //Parse the data as a GeoJSON Feature Collection.
        FeatureCollection fc = FeatureCollection.fromJson(result);

        //Add the feature collection to the data source.
        source.add(fc);

        //Optionally, update the maps camera to focus in on the data.

        //Calculate the bounding box of all the data in the Feature Collection.
        BoundingBox bbox = MapMath.fromData(fc);

        //Update the maps camera so it is focused on the data.
        map.setCamera(
            bounds(bbox),
            padding(20));
    });
//Create a data source and add it to the map.
DataSource source = new DataSource();
map.sources.add(source);

//Import the GeoJSON data and add it to the data source.
Utils.importData("SamplePoiDataSet.json", this) { 
    result: String? ->
        //Parse the data as a GeoJSON Feature Collection.
            val fc = FeatureCollection.fromJson(result!!)

        //Add the feature collection to the data source.
        source.add(fc)

        //Optionally, update the maps camera to focus in on the data.

        //Calculate the bounding box of all the data in the Feature Collection.
        val bbox = MapMath.fromData(fc);

        //Update the maps camera so it is focused on the data.
        map.setCamera(
            bounds(bbox),

            //Padding added to account for pixel size of rendered points.
            padding(20)
        )
    }

Özelliği güncelleştirme

sınıfı, DataSource özellik eklemeyi ve kaldırmayı kolaylaştırır. Bir özelliğin geometrisini veya özelliklerini güncelleştirmek için veri kaynağındaki özelliğin değiştirilmesi gerekir. Bir özelliği güncelleştirmek için kullanılabilecek iki yöntem vardır:

  1. İstenen güncelleştirmelerle yeni özellikleri oluşturun ve yöntemini kullanarak setShapes veri kaynağındaki tüm özellikleri değiştirin. Bir veri kaynağındaki tüm özellikleri güncelleştirmek istediğinizde bu yöntem düzgün çalışır.
DataSource source;

private void onReady(AzureMap map) {
    //Create a data source and add it to the map.
    source = new DataSource();
    map.sources.add(source);

    //Create a feature and add it to the data source.
    Feature myFeature = Feature.fromGeometry(Point.fromLngLat(0,0));
    myFeature.addStringProperty("Name", "Original value");

    source.add(myFeature);
}

private void updateFeature(){
    //Create a new replacement feature with an updated geometry and property value.
    Feature myNewFeature = Feature.fromGeometry(Point.fromLngLat(-10, 10));
    myNewFeature.addStringProperty("Name", "New value");

    //Replace all features to the data source with the new one.
    source.setShapes(myNewFeature);
}
var source: DataSource? = null

private fun onReady(map: AzureMap) {
    //Create a data source and add it to the map.
    source = DataSource()
    map.sources.add(source)

    //Create a feature and add it to the data source.
    val myFeature = Feature.fromGeometry(Point.fromLngLat(0.0, 0.0))
    myFeature.addStringProperty("Name", "Original value")
    source!!.add(myFeature)
}

private fun updateFeature() {
    //Create a new replacement feature with an updated geometry and property value.
    val myNewFeature = Feature.fromGeometry(Point.fromLngLat(-10.0, 10.0))
    myNewFeature.addStringProperty("Name", "New value")

    //Replace all features to the data source with the new one.
    source!!.setShapes(myNewFeature)
}
  1. Özellik örneğini bir değişkende izleyin ve kaldırmak için veri kaynakları remove yöntemine geçirin. İstenen güncelleştirmelerle yeni özellikleri oluşturun, değişken başvuruyu güncelleştirin ve yöntemini kullanarak add veri kaynağına ekleyin.
DataSource source;
Feature myFeature;

private void onReady(AzureMap map) {
    //Create a data source and add it to the map.
    source = new DataSource();
    map.sources.add(source);

    //Create a feature and add it to the data source.
    myFeature = Feature.fromGeometry(Point.fromLngLat(0,0));
    myFeature.addStringProperty("Name", "Original value");

    source.add(myFeature);
}

private void updateFeature(){
    //Remove the feature instance from the data source.
    source.remove(myFeature);

    //Get properties from original feature.
    JsonObject props = myFeature.properties();

    //Update a property.
    props.addProperty("Name", "New value");

    //Create a new replacement feature with an updated geometry.
    myFeature = Feature.fromGeometry(Point.fromLngLat(-10, 10), props);

    //Re-add the feature to the data source.
    source.add(myFeature);
}
var source: DataSource? = null
var myFeature: Feature? = null

private fun onReady(map: AzureMap) {
    //Create a data source and add it to the map.
    source = DataSource()
    map.sources.add(source)

    //Create a feature and add it to the data source.
    myFeature = Feature.fromGeometry(Point.fromLngLat(0.0, 0.0))
    myFeature.addStringProperty("Name", "Original value")
    source!!.add(myFeature)
}

private fun updateFeature() {
    //Remove the feature instance from the data source.
    source!!.remove(myFeature)

    //Get properties from original feature.
    val props = myFeature!!.properties()

    //Update a property.
    props!!.addProperty("Name", "New value")

    //Create a new replacement feature with an updated geometry.
    myFeature = Feature.fromGeometry(Point.fromLngLat(-10.0, 10.0), props)

    //Re-add the feature to the data source.
    source!!.add(myFeature)
}

İpucu

Düzenli olarak güncelleştirilecek bazı verileriniz varsa ve nadiren değiştirilecek diğer verileriniz varsa, bunları ayrı veri kaynağı örneklerine bölmek en iyisidir. Bir veri kaynağında bir güncelleştirme gerçekleştiğinde, haritayı veri kaynağındaki tüm özellikleri yeniden boyamaya zorlar. Bu veriler bölünerek yalnızca düzenli olarak güncelleştirilen özellikler, bir veri kaynağında bir güncelleştirme gerçekleştiğinde yeniden boyanırken diğer veri kaynağındaki özelliklerin yeniden boyanmış olması gerekmez. Bu, performansa yardımcı olur.

Vektör kutucuğu kaynağı

Vektör kutucuğu kaynağı, vektör kutucuğu katmanına erişmeyi açıklar. VectorTileSource Vektör kutucuğu kaynağının örneğini oluşturmak için sınıfını kullanın. Vektör kutucuğu katmanları kutucuk katmanlarına benzer, ancak aynı değildir. Kutucuk katmanı, raster bir görüntüdür. Vektör kutucuğu katmanları PBF biçiminde sıkıştırılmış bir dosyadır. Bu sıkıştırılmış dosya vektör eşleme verilerini ve bir veya daha fazla katmanı içerir. Dosya, her katmanın stiline göre istemci üzerinde işlenebilir ve stillendirilebilir. Vektör kutucuğundaki veriler nokta, çizgi ve çokgen biçiminde coğrafi özellikler içerir. Raster kutucuk katmanları yerine vektör kutucuğu katmanlarını kullanmanın çeşitli avantajları vardır:

  • Vektör kutucuğunun dosya boyutu genellikle eşdeğer bir raster kutucuğundan çok daha küçüktür. Bu nedenle daha az bant genişliği kullanılır. Daha düşük gecikme süresi, daha hızlı bir harita ve daha iyi bir kullanıcı deneyimi anlamına gelir.
  • Vektör kutucukları istemcide işlendiğinden, görüntülendikleri cihazın çözünürlüğüne uyarlanır. Sonuç olarak, işlenen haritalar kristal netlikli etiketlerle daha iyi tanımlanmış görünür.
  • Yeni stil istemciye uygulanabildiğinden, vektör haritalarındaki verilerin stilini değiştirmek için verilerin yeniden indirilmesi gerekmez. Buna karşılık, bir tarama kutucuğu katmanının stilini değiştirmek için genellikle sunucudan kutucukların yüklenmesi ve ardından yeni stilin uygulanması gerekir.
  • Veriler vektör biçiminde teslim edildikten sonra, verileri hazırlamak için daha az sunucu tarafı işleme gerekir. Sonuç olarak, daha yeni veriler daha hızlı kullanılabilir hale getirilebilir.

Azure HaritalarMapbox Vektör Kutucuğu Belirtimi, açık bir standart. Azure Haritalar, platformun bir parçası olarak aşağıdaki vektör kutucukları hizmetlerini sağlar:

İpucu

web SDK'sı ile Azure Haritalar işleme hizmetinden vektör veya raster görüntü kutucuklarını kullanırken yerine yer tutucusunu azmapsdomain.invalidkullanabilirsinizatlas.microsoft.com. Bu yer tutucu, eşleme tarafından kullanılan etki alanıyla değiştirilir ve aynı kimlik doğrulama ayrıntılarını da otomatik olarak ekler. Bu, Microsoft Entra kimlik doğrulaması kullanılırken işleme hizmetiyle kimlik doğrulamasını büyük ölçüde basitleştirir.

Haritada bir vektör kutucuğu kaynağından verileri görüntülemek için kaynağı veri işleme katmanlarından birine bağlayın. Vektör kaynağı kullanan tüm katmanlar seçeneklerde bir sourceLayer değer belirtmelidir. Aşağıdaki kod, Azure Haritalar trafik akışı vektör kutucuğu hizmetini vektör kutucuğu kaynağı olarak yükler ve ardından çizgi katmanı kullanarak harita üzerinde görüntüler. Bu vektör kutucuğu kaynağı, kaynak katmanında "Trafik akışı" adlı tek bir veri kümesine sahiptir. Bu veri kümesindeki çizgi verileri, rengi seçmek ve çizgilerin boyutunu ölçeklendirmek için bu kodda kullanılan adlı traffic_level bir özelliğe sahiptir.

//Formatted URL to the traffic flow vector tiles, with the maps subscription key appended to it.
String trafficFlowUrl = "https://azmapsdomain.invalid/traffic/flow/tile/pbf?api-version=1.0&style=relative&zoom={z}&x={x}&y={y}";

//Create a vector tile source and add it to the map.
VectorTileSource source = new VectorTileSource(
    tiles(new String[] { trafficFlowUrl }),
    maxSourceZoom(22)
);
map.sources.add(source);

//Create a layer for traffic flow lines.
LineLayer layer = new LineLayer(source,
    //The name of the data layer within the data source to pass into this rendering layer.
    sourceLayer("Traffic flow"),

    //Color the roads based on the traffic_level property.
    strokeColor(
        interpolate(
            linear(),
            get("traffic_level"),
            stop(0, color(Color.RED)),
            stop(0.33, color(Color.YELLOW)),
            stop(0.66, color(Color.GREEN))
        )
    ),

    //Scale the width of roads based on the traffic_level property.
    strokeWidth(
        interpolate(
            linear(),
            get("traffic_level"),
            stop(0, 6),
            stop(1,1)
        )
    )
);

//Add the traffic flow layer below the labels to make the map clearer.
map.layers.add(layer, "labels");
//Formatted URL to the traffic flow vector tiles, with the maps subscription key appended to it.
val trafficFlowUrl = "https://azmapsdomain.invalid/traffic/flow/tile/pbf?api-version=1.0&style=relative&zoom={z}&x={x}&y={y}"

//Create a vector tile source and add it to the map.
val source = VectorTileSource(
    tiles(arrayOf(trafficFlowUrl)),
    maxSourceZoom(22)
)
map.sources.add(source)

//Create a layer for traffic flow lines.
val layer = LineLayer(
    source,  //The name of the data layer within the data source to pass into this rendering layer.
    sourceLayer("Traffic flow"),  //Color the roads based on the traffic_level property.
    strokeColor(
        interpolate(
            linear(),
            get("traffic_level"),
            stop(0, color(Color.RED)),
            stop(0.33, color(Color.YELLOW)),
            stop(0.66, color(Color.GREEN))
        )
    ),  //Scale the width of roads based on the traffic_level property.
    strokeWidth(
        interpolate(
            linear(),
            get("traffic_level"),
            stop(0, 6),
            stop(1, 1)
        )
    )
)

//Add the traffic flow layer below the labels to make the map clearer.
map.layers.add(layer, "labels")

Trafik akışı düzeylerini gösteren renk kodlu yol çizgileriyle harita

Veri kaynağını katmana bağlama

Veriler, işleme katmanları kullanılarak haritada işlenir. Bir veya daha fazla işleme katmanı tek bir veri kaynağına başvurabilir. Aşağıdaki işleme katmanları bir veri kaynağı gerektirir:

Aşağıdaki kodda bir veri kaynağının nasıl oluşturulacağı, haritaya nasıl ekleneceği ve bir kabarcık katmanına nasıl bağlanacağı gösterilmektedir. Ardından GeoJSON noktası verilerini uzak bir konumdan veri kaynağına aktarın.

//Create a data source and add it to the map.
DataSource source = new DataSource();

//Import the geojson data and add it to the data source.
source.importDataFromUrl("URL_or_FilePath_to_GeoJSON_data");

//Add data source to the map.
map.sources.add(source);

//Create a layer that defines how to render points in the data source and add it to the map.
BubbleLayer layer = new BubbleLayer(source);
map.layers.add(layer);
//Create a data source and add it to the map.
val source = DataSource()

//Import the geojson data and add it to the data source.
source.importDataFromUrl("URL_or_FilePath_to_GeoJSON_data")

//Add data source to the map.
map.sources.add(source)

Bu veri kaynaklarına bağlanmayen daha fazla işleme katmanı vardır, ancak bunlar işleme için verileri doğrudan yükler.

  • Kutucuk katmanı - haritanın üst kısmında bir raster kutucuğu katmanının yerini alır.

Birden çok katmana sahip bir veri kaynağı

Tek bir veri kaynağına birden çok katman bağlanabilir. Bu seçeneğin yararlı olduğu birçok farklı senaryo vardır. Örneğin, kullanıcının çokgen çizdiği senaryoyu göz önünde bulundurun. Kullanıcı haritaya nokta ekledikçe çokgen alanını işlemeli ve doldurmalıyız. Çokgeni ana hat haline getirmek için stilli çizgi eklemek, kullanıcı çizerken çokgenin kenarlarını görmeyi kolaylaştırır. Çokgendeki tek bir konumu rahatça düzenlemek için her konumun üzerine raptiye veya işaretçi gibi bir tutamaç ekleyebiliriz.

Tek bir veri kaynağından veri işlemeyi gösteren birden çok katmanı gösteren harita

Çoğu eşleme platformunda, çokgendeki her konum için bir çokgen nesnesine, çizgi nesnesine ve raptiyeye ihtiyacınız vardır. Çokgen değiştirildiğinde, hızla karmaşık hale gelebilen çizgi ve raptiyeleri el ile güncelleştirmeniz gerekir.

Azure Haritalar ile, aşağıdaki kodda gösterildiği gibi tek ihtiyacınız olan veri kaynağında tek bir çokgendir.

//Create a data source and add it to the map.
DataSource source = new DataSource();
map.sources.add(source);

//Create a polygon and add it to the data source.
source.add(Polygon.fromLngLats(/* List of points */));

//Create a polygon layer to render the filled in area of the polygon.
PolygonLayer polygonLayer = new PolygonLayer(source,
    fillColor("rgba(255,165,0,0.2)")
);

//Create a line layer for greater control of rendering the outline of the polygon.
LineLayer lineLayer = new LineLayer(source,
    strokeColor("orange"),
    strokeWidth(2f)
);

//Create a bubble layer to render the vertices of the polygon as scaled circles.
BubbleLayer bubbleLayer = new BubbleLayer(source,
    bubbleColor("orange"),
    bubbleRadius(5f),
    bubbleStrokeColor("white"),
    bubbleStrokeWidth(2f)
);

//Add all layers to the map.
map.layers.add(new Layer[] { polygonLayer, lineLayer, bubbleLayer });
//Create a data source and add it to the map.
val source = DataSource()
map.sources.add(source)

//Create a polygon and add it to the data source.
source.add(Polygon.fromLngLats())

//Create a polygon layer to render the filled in area of the polygon.
val polygonLayer = PolygonLayer(
    source,
    fillColor("rgba(255,165,0,0.2)")
)

//Create a line layer for greater control of rendering the outline of the polygon.
val lineLayer = LineLayer(
    source,
    strokeColor("orange"),
    strokeWidth(2f)
)

//Create a bubble layer to render the vertices of the polygon as scaled circles.
val bubbleLayer = BubbleLayer(
    source,
    bubbleColor("orange"),
    bubbleRadius(5f),
    bubbleStrokeColor("white"),
    bubbleStrokeWidth(2f)
)

//Add all layers to the map.
map.layers.add(arrayOf<Layer>(polygonLayer, lineLayer, bubbleLayer))

İpucu

yöntemini kullanarak map.layers.add haritaya katman eklerken, mevcut katmanın kimliği veya örneği ikinci parametre olarak geçirilebilir. Bu, bu haritaya mevcut katmanın altına eklenen yeni katmanı eklemesini bildirir. Katman kimliği geçirmenin yanı sıra bu yöntem aşağıdaki değerleri de destekler.

  • "labels" - Yeni katmanı harita etiketi katmanlarının altına ekler.
  • "transit" - Yeni katmanı harita yol ve ulaşım katmanlarının altına ekler.

Sonraki adımlar

Haritalarınıza eklenecek daha fazla kod örneği için aşağıdaki makalelere bakın: