Программа составления заявлений из kml. Создание KML в ArcGIS for Desktop

Объявление

Формат файлов KML Misc

Файлы KML хранятся в формате XML и изначально разработаны для картографической программы Keyhole. В 2004 году компания Google купила Keyhole Inc., и именно поэтому файлы KML теперь активно используется службами Google, связанными с картографией - Google Maps и Google Earth.

Технические сведения о файлах KML

Файлы KML содержат информацию, которая хранится в формате XML. Эти сведения включают в себя как изображения, так и более простые данные - линии, многоугольники и точки. Такие файлы используются для хранения информации о конкретном месте на карте. Файл KML позволяет пользователю не только отметить на карте местоположение, но и добавить контент (в формате HTML), текстуру и вид под разными углами. Чтобы открыть файлы KML в Google Maps, все, что требуется - это сам файл KML, размещенный в Интернете. С помощью отдельной ссылки расширения в строке поиска Google Maps произойдет его открытие.

Дополнительная информация о формате KML

Первым вариантом, при помощи которого можно открывать формат KMZ, является приложение Google Earth. Это универсальная картографическая программа от всемирно известной компании.

Все что вам придется сделать - это в запущенном ПО выбрать пункт меню «Файл» - «Открыть». На следующем этапе выбираете папку, в которой находится сам файл, выделяете его и нажимаете кнопку «Открыть».

Еще один способ - перетаскивание файла из «Проводника» в область, где отображаются карты.

Использование приложения Google SketchUp

Данная программа используется для трехмерного моделирования, а в файле с расширением KMZ могут храниться всевозможные 3D-модели объектов, необходимые для реалистичной демонстрации местности.

Для его открытия жмем Import-File. Как и в предыдущем случае, находим нужную папку, выбираем в ней нужный файл и жмем Import.

Геоинформационное ПО Global Mapper

Эта программа поддерживает большое количество картографических форматов, в том числе и упомянутый в данной статье. Благодаря приложению содержащиеся в нем данные можно не только редактировать, но и преобразовывать.

Открытие осуществляется при помощи пункта меню Open Data File(s) - File. Далее все аналогично предыдущим вариантам.

Геоинформационная платформа ArcGIS Server

Мы будем использовать ее настольную версию - ArcGIS Explorer. Файл KMZ, который тоже используют в данном приложении, помогает задавать координаты необходимого объекта.

Открыть его можно путем перетаскивания из «Проводника» Windows непосредственно в рабочую область ПО.

Расширение файла .kml
Категория файлов
Файл-пример (2,05 KiB)
Связанные программы Blender (Windows, Mac & Linux)
Blue Marble Geographics Global Mapper (Windows)
ESRI ArcGIS for Desktop (Windows)
Google Earth (Windows, Mac & Linux)
Google Maps (Web)
Merkaartor (Windows, Mac & Linux)
Keyhole PRO (Windows & Mac)

KML is a file format used to display geographic data in an Earth browser such as Google Earth. KML uses a tag-based structure with nested elements and attributes and is based on the XML standard. All tags are case-sensitive and must appear exactly as they are listed in the . The Reference indicates which tags are optional. Within a given element, tags must appear in the order shown in the Reference.

If you"re new to KML, explore this document and the accompanying samples files () to begin learning about the basic structure of a KML file and the most commonly used tags. The first section describes features that can be created with the Google Earth user interface. These features include placemarks, descriptions, ground overlays, paths, and polygons. The second section describes features that require authoring KML with a text editor. When a text file is saved with a .kml or .kmz extension, Earth browsers know how to display it.

Tip: To see the KML "code" for a feature in Google Earth, you can simply right-click the feature in the 3D Viewer of Google Earth and select Copy. Then Paste the contents of the clipboard into any text editor. The visual feature displayed in Google Earth is converted into its KML text equivalent. Be sure to experiment with this feature.

For a discussion of how to use some of the key features in KML, see the .

Table of Contents

Basic KML Documents

The simplest kind of KML documents are those that can be authored directly in Google Earth—that is, you don"t need to edit or create any KML in a text editor. Placemarks, ground overlays, paths, and polygons can all be authored directly in Google Earth.

Placemarks

A Placemark is one of the most commonly used features in Google Earth. It marks a position on the Earth"s surface, using a yellow pushpin as the icon. The simplest Placemark includes only a Element, which specifies the location of the Placemark. You can specify a name and a custom icon for the Placemark, and you can also add other geometry elements to it.

As an example, enable the "Absolute Positioning: Top left" folder in the file and you will see a screen overlay at the top left of the view window. This was created with the following KML code:




Absolute Positioning: Top left

http://сайт/kml/documentation/images/top_left.jpg






Positioning is controlled by mapping a point in the image specified by to a point on the screen specified by . In this case, the top-left corner of the image (0,1) has been made coincident with the same point on the screen.

Check the other examples in the folder to see how it is possible to obtain other fixed positions, and to create images that size dynamically with screen size. (Note that xunits and yunits can also be specified as "pixels" for precision control.) For further detail, see the .

Network Links

A network link contains a element with an (a hypertext reference) that loads a file. The can be a local file specification or an absolute URL. Despite the name, a does not necessarily load files from the network.

The in a link specifies the location of any of the following:

  • An image file used by icons in icon styles, ground overlays, and screen overlays
  • A model file used in the element
  • A KML or KMZ file loaded by a Network Link

The specified file can be either a local file or a file on a remote server. In their simplest form, network links are a useful way to split one large KML file into smaller, more manageable files on the same computer.

So far, all of our examples have required that the KML code be delivered to Google Earth from the local machine. Network links give you the power to serve content from a remote location and are commonly used to distribute data to large numbers of users. In this way, if the data needs to be amended, it has to be changed only at the source location, and all users receive the updated data automatically.

CGI Scripting for KML

In addition to pointing to files containing static data, a network link"s can point to data that is dynamically generated—for example, by a CGI script located on a network server. With some knowledge of a scripting language such as PHP, Python, or Perl, you can create a script that delivers a stream (or file) of KML data to each network link.

Two things are necessary for delivering KML through a network CGI:

When a call is made from the client (Google Earth) to the server, the server must (1) return a response code of HTTP 200 and (2) set the response"s content type to text/plain or application/vnd.google-earth.kml+xml.

The response must be valid KML. For complex applications, proper error handling is very important.

Tip: A simple way to handle errors is to parse the server"s error as the text for a folder name. For example, you could have the server return database inaccessible as a string. This is more informative (and more user-friendly) than letting the connection drop.

The following examples use Python, but they are equally valid in any other scripting language.

Generating a Random Placemark

The following Python script generates random integer values for latitude and longitude and then inserts those values into the element of a Whenever the network link is refreshed, the Python script runs again and generates KML with new latitude and longitude values.

#!/usr/bin/python import random latitude = random.randrange(-90, 90) longitude = random.randrange(-180, 180) kml = ("\n" "\n" "\n" "Random Placemark\n" "\n" "%d,%d\n" "\n" "\n" "") %(longitude, latitude) print "Content-Type: application/vnd.google-earth.kml+xml\n" print kml

Here is an example of a KML file containing a Network Link that loads this Python script:




Network Links
0
0
Network link example 1

Random Placemark
0
0
A simple server-side script that generates a new random
placemark on each call

0
0

http://yourserver.com /cgi-bin/randomPlacemark.py



View-Based Refresh Queries

A standard network link is a uni-directional link: data flows only from the server to Google Earth. The view-based refresh enables bi-directional communication. When the view-based refresh is active, Google Earth returns the view coordinates to the server at a specified time. This may be every n seconds, minutes, or hours, or once a certain amount of time has elapsed since the view stopped moving. See in the KML 2.2 Reference.

The coordinates are returned to the server by means of an HTTP GET that appends the coordinates as follows (this is the default bounding box information):

GET /path/to/sever/script/query?BBOX= HTTP/1.1

If the request were made while the user was looking down on San Francisco, the coordinates might look as follows:

GET /path/to/server/script/query?BBOX=-122.497790,37.730385,-122.380087,37.812331 HTTP/1.1

This feature can be used for some very creative applications, but to get you started, a simple example is presented below.

Tracking a Point Directly Under Your View

The following server-side Python script parses the return message sent by Google Earth and responds with a Placemark at the center of the screen. Each time the Network Link is refreshed, a new Placemark is generated.

#!/usr/bin/python import cgi url = cgi.FieldStorage() bbox = url["BBOX"].value bbox = bbox.split(",") west = float(bbox) south = float(bbox) east = float(bbox) north = float(bbox) center_lng = ((east - west) / 2) + west center_lat = ((north - south) / 2) + south kml = ("\n" "\n" "\n" "View-centered placemark\n" "\n" "%.6f,%.6f\n" "\n" "\n" "") %(center_lng, center_lat) print "Content-Type: application/vnd.google-earth.kml+xml\n" print kml

And here is the KML for the Network Link that loads the Python script:




Network Links
0
0
Network link example 2

View Centered Placemark
0
0
The view-based refresh allows the remote server to calculate
the center of your screen and return a placemark.

0
0

http://yourserver.com /cgi-bin/viewCenteredPlacemark.py

2
onStop
1



The principle illustrated in this example can be used for some very complex applications. For example, if you have a database of geographic information, you can extract the coordinates of the viewer, make a call to the database for the data specific to the view, and return it to Google Earth as KML.

3 KML MIME Types

When responding to a request from Google Earth (or any Earth browser), a KML server must follow a certain set of rules so that Google Earth can correctly interpret its responses.

Upon success, the server must return a response code of HTTP 200 and set the response"s content-type to a suitable MIME type, as described here.

Google Earth reads KML and KMZ files. The MIME type for KML files is

  • application/vnd.google-earth.kml+xml

The MIME type for KMZ files is

  • application/vnd.google-earth.kmz

For Apache, add these lines to the httpd.conf file:

  • AddType application/vnd.google-earth.kml+xml .kml
  • AddType application/vnd.google-earth.kmz .kmz

See the Microsoft documentation for details on setting up MIME types on Microsoft"s IIS.

The body of the response must contain valid KML data, including the XML declaration (). If the server returns invalid KML, the Network Link will stop, deactivate, and output an error message.

What"s Next?

Ready for more? Check out the , which describes key KML features. Also, browse the for information on specific elements.

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License , and code samples are licensed under the Apache 2.0 License . For details, see our . Java is a registered trademark of Oracle and/or its affiliates.

При наличии на компьютере установленной антивирусной программы можносканировать все файлы на компьютере, а также каждый файл в отдельности . Можно выполнить сканирование любого файла, щелкнув правой кнопкой мыши на файл и выбрав соответствующую опцию для выполнения проверки файла на наличие вирусов.

Например, на данном рисунке выделен файл my-file.kml , далее необходимо щелкнуть правой кнопкой мыши по этому файлу, и в меню файла выбрать опцию «сканировать с помощью AVG» . При выборе данного параметра откроется AVG Antivirus, который выполнит проверку данного файла на наличие вирусов.


Иногда ошибка может возникнуть в результате неверной установки программного обеспечения , что может быть связано с проблемой, возникшей в процессе установки. Это может помешать вашей операционной системе связать ваш файл KML с правильным прикладным программным средством , оказывая влияние на так называемые «ассоциации расширений файлов» .

Иногда простая переустановка ESRI ArcGIS for Desktop может решить вашу проблему, правильно связав KML с ESRI ArcGIS for Desktop. В других случаях проблемы с файловыми ассоциациями могут возникнуть в результате плохого программирования программного обеспечения разработчиком, и вам может потребоваться связаться с разработчиком для получения дополнительной помощи.


Совет: Попробуйте обновить ESRI ArcGIS for Desktop до последней версии, чтобы убедиться, что установлены последние исправления и обновления.


Это может показаться слишком очевидным, но зачастую непосредственно сам файл KML может являться причиной проблемы . Если вы получили файл через вложение электронной почты или загрузили его с веб-сайта, и процесс загрузки был прерван (например, отключение питания или по другой причине), файл может повредиться . Если возможно, попробуйте получить новую копию файла KML и попытайтесь открыть его снова.


Осторожно: Поврежденный файл может повлечь за собой возникновение сопутствующего ущерба предыдущей или уже существующей вредоносной программы на вашем ПК, поэтому очень важно, чтобы на вашем компьютере постоянно работал обновленный антивирус.


Если ваш файл KML связан с аппаратным обеспечением на вашем компьютере , чтобы открыть файл вам может потребоваться обновить драйверы устройств , связанных с этим оборудованием.

Эта проблема обычно связана с типами мультимедийных файлов , которые зависят от успешного открытия аппаратного обеспечения внутри компьютера, например, звуковой карты или видеокарты . Например, если вы пытаетесь открыть аудиофайл, но не можете его открыть, вам может потребоваться обновить драйверы звуковой карты .


Совет: Если при попытке открыть файл KML вы получаете сообщение об ошибке, связанной с.SYS file , проблема, вероятно, может быть связана с поврежденными или устаревшими драйверами устройств , которые необходимо обновить. Данный процесс можно облегчить посредством использования программного обеспечения для обновления драйверов, такого как DriverDoc .


Если шаги не решили проблему , и у вас все еще возникают проблемы с открытием файлов KML, это может быть связано с отсутствием доступных системных ресурсов . Для некоторых версий файлов KML могут потребоваться значительный объем ресурсов (например, память/ОЗУ, вычислительная мощность) для надлежащего открытия на вашем компьютере. Такая проблема встречается достаточно часто, если вы используете достаточно старое компьютерное аппаратное обеспечение и одновременно гораздо более новую операционную систему.

Такая проблема может возникнуть, когда компьютеру трудно справиться с заданием, так как операционная система (и другие службы, работающие в фоновом режиме) могут потреблять слишком много ресурсов для открытия файла KML . Попробуйте закрыть все приложения на вашем ПК, прежде чем открывать Keyhole Markup Language File. Освободив все доступные ресурсы на вашем компьютере вы обеспечите налучшие условия для попытки открыть файл KML.


Если вы выполнили все описанные выше шаги , а ваш файл KML по-прежнему не открывается, может потребоваться выполнить обновление оборудования . В большинстве случаев, даже при использовании старых версий оборудования, вычислительная мощность может по-прежнему быть более чем достаточной для большинства пользовательских приложений (если вы не выполняете много ресурсоемкой работы процессора, такой как 3D-рендеринг, финансовое/научное моделирование или интенсивная мультимедийная работа). Таким образом, вполне вероятно, что вашему компьютеру не хватает необходимого объема памяти (чаще называемой «ОЗУ», или оперативной памятью) для выполнения задачи открытия файла.

Формат KML является расширением, в котором сохраняются географические данные объектов в программе Google Earth. К такой информации относятся метки на карте, произвольный участок в виде многоугольника или линий, трехмерная модель и изображение части карты.

Рассмотрим приложения, которые взаимодействуют с данным форматом.

Google Earth

    1. После запуска нажимаем на «Открыть» в главном меню.

  1. Находим директорию с исходным объектом. В нашем случае файл содержит информацию о местоположении. Кликаем по нему и жмем на «Открыть» .

Интерфейс программы с указанием местоположения в виде метки.

Блокнот

Блокнот - встроенное приложение Windows для создания текстовых документов. Может также выступать в роли редактора кода определенных форматов.

    1. Запустите данный софт. Для просмотра файла надо выбрать «Открыть» в меню.

  1. Выбираем «Все файлы» в соответствующем поле. Выделив искомый объект, нажимаем на «Открыть» .

Визуальное отображение содержимого файла в Блокноте.

Можно сказать, что расширение KML имеет малое распространение, и используется исключительно в Google Earth, а просмотр такого файла через Блокнот мало кому будет полезен.



error: Content is protected !!