Расширение kml. Что такое расширение файла KML? Конвертирование файла KML

KML (Keyhole Markup Language - язык разметки Keyhole) — это формат файлов, который используется отображения географических данных в программах Google Планета Земля, Карты Google и Карты Google для мобильных устройств.

KML использует основанную на тегах структуру с вложенными элементами и атрибутами и создан на основе стандарта XML.

Для создания файлов KML можно использовать программу Google Планета Земля (Google Earth), редактор XML или обычный текстовый редактор.

Файлы KML и связанные с ними изображения (при наличии) можно сжимать с помощью формата ZIP в архивы KMZ.

С помощью файлов KML можно:

  • устанавливать различные значки и делать подписи для обозначения мест на поверхности Земли,
  • создавать различные ракурсы для выбранных объектов, изменяя положение камеры,
  • использовать различные накладываемые изображения,
  • определять стили для настройки отображения объекта, применять код HTML для создания гиперссылок и встроенных изображений,
  • использовать папки для иерархической группировки элементов,
  • динамически получать и обновлять файлы KML из удаленных или локальных узлов сети,
  • получать данные KML в соответствии с изменениями в средстве трехмерного просмотра,
  • отображать текстурные трехмерные объекты COLLADA

В качестве объектов в файлах формата KML могут быть использованы:

Метки (объект Placemark) – самый простой элемент, задает метку – обозначение положения на поверхности Земли с помощью значка в виде желтой кнопки.

Пути – линии определенной толщины и цвета

Многоугольники — определяется цвет линий и цвет подписи.

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

Трёхмерная модель — позволяет подключать описание трёхмерных объектов (например, зданий и сооружений). Трёхмерную модель можно задать двумя способами: заданием высоты плоских фигур (вытягиванием) и ссылкой на полноценную модель в формате COLLADA (Google SketchUp).

Простейший пример файла KML.



Дворец спорта
Дворец спорта «Нагорный» просп. Гагарина, 29
43.979459,56.291908,0


Опишу структуру этого файла.

Первая строка — заголовок XML. Это 1-я строка в каждом файле KML. Перед этой строкой не должно быть пробелов или символов.

Вторая строка – служит для объявления пространства имен KML. Это 2-я строка в каждом файле KML 2.1.

Объект Placemark, содержащий следующие элементы:

— name, ярлык, используемый для обозначения метки

— description, описание, появляющееся в окне комментария, прикрепленном к метке

— Point, указывает положение метки на поверхности Земли (долгота, широта и дополнительно высота).

Этот файл Вы можете загрузить в программе Google Планета Земля (Google Earth) выбрав в меню Файл – Открыть.

Его также можно загрузить использую API карт Google.

Код примера:

Пример использования Google Earth на сайте

function initialize() {if (GBrowserIsCompatible()) {geoXml = new GGeoXml(«http://remont.cek.ru/xml/prim_kml_1.kml»);

var map = new GMap2(document.getElementById(«map_canvas»));

map.setCenter(new GLatLng(56.291908,43.979459), 15);

map.setMapType(G_SATELLITE_MAP);

map.addControl(new GSmallMapControl());

map.addControl(new GMapTypeControl());

map.addOverlay(geoXml);

Если загрузить его в браузере мы увидим

Вы также можете просмотреть файл KML на Картах Google.

Предварительно необходимо чтобы Ваш файл KML должен быть размещен на веб-сайте в Интернете.

С начала нужно зайти по адресу http://maps.google.ru/

Затем в строке поиска ввести адрес Вашего KML-файла в интернете, например, http://сайт/examples/kml/prim_kml_1.kml и нажать на кнопку «Поиск на карте».

Ваш KML-файл отобразиться на карте Google.

Продолжение следует…

KMZ файлы хранят местонахождение на карте для просмотра в Google Earth, глобальной программы отображения. Они обеспечивают вид с высоты птичьего полета местах по всей территории США и других регионах мира. Меток может включать в себя пользовательское имя и координаты широты и долготы местоположения. KML файлы очень часто распространяются в KMZ файлы, которые запакованы в формате KML файлы с расширением.kmz. Кихол Markup Language (KML) является XML-нотация для выражения географической аннотацию и визуализации в Интернет на основе, двумерных карт и трехмерных браузеров Земли. KML был разработан для использования с Google Earth, который первоначально был назван Keyhole Earth Viewer. Она была создана Keyhole, Inc, которая была приобретена компанией Google в 2004 году KMZ файлы могут быть открыты разархивированием их с утилитой сжатия, таких как WinZip на Windows, MacZip для пользователей Macintosh, и Zip и разархивировать для систем UNIX.

Файлы с расширением KMZ используются популярной программой - Google Планета Земля, и они содержат местоположения карт, используемых в этом программном обеспечении.

KMZ-файлы - это архивы, состоящие из основных (обычно doc.kml ) и потенциально дополнительных файлов, таких как: пользовательские скины, изображения, значки или 3D-модели. Весь этот контент упакован с использованием метода ZIP, который использует простой алгоритм сжатия - DEFLATE - который обеспечивает более высокую совместимость с большим количеством приложений. В соответствии с соглашением файлы doc.kml находятся в основной папке, а дополнительные файлы - в подпапках.

Файлы KMZ могут содержать такие данные как:

  • маркеры для мест с нетипичными названиями,
  • географические координаты - долгота и параллель,
  • Данные 3D-модели, с некоторыми ограничениями.

Благодаря файлам KMZ, Google Планета Земля обеспечивает отображение с высоты птичьего полета во многих местах. Данные, содержащиеся в файлах KMZ, могут отображаться в любом геопространственном программном обеспечении, поддерживающем кодирование KML.

намек

Файлы KMZ также поддерживаются Google Maps Online. Требуется загрузить файл KMZ на FTP-сервер и вставить ссылку в окно поиска Google Maps. Кроме того, пользователь может сделать это вручную, разместив ссылку непосредственно на следующий адрес:

Программы, обслуживающие файл KMZ Конвертирование файла KMZ

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

Конвертирование файла с расширением KMZ в другой формат

Конвертирование файлов другого формата в файл KMZ

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

Что еще может вызвать проблемы?

Поводов того, что Вы не можете открыть файл KMZ может быть больше (не только отсутствие соответствующего приложения).
Во-первых - файл KMZ может быть неправильно связан (несовместим) с установленным приложением для его обслуживания. В таком случае Вам необходимо самостоятельно изменить эту связь. С этой целью нажмите правую кнопку мышки на файле KMZ, который Вы хотите редактировать, нажмите опцию "Открыть с помощью" а затем выберите из списка программу, которую Вы установили. После такого действия, проблемы с открытием файла KMZ должны полностью исчезнуть.
Во вторых - файл, который Вы хотите открыть может быть просто поврежден. В таком случае лучше всего будет найти новую его версию, или скачать его повторно с того же источника (возможно по какому-то поводу в предыдущей сессии скачивание файла KMZ не закончилось и он не может быть правильно открыт).

Вы хотите помочь?

Если у Вас есть дополнительная информация о расширение файла KMZ мы будем признательны, если Вы поделитесь ею с пользователями нашего сайта. Воспользуйтесь формуляром, находящимся и отправьте нам свою информацию о файле KMZ.

Файл KMZ содержит геолокационные данные, например метку о местоположении, и в основном используется в картографических приложениях. Часто такой информацией могут обмениваться пользователи по всему миру и поэтому вопрос открытия данного формата является актуальным.

Итак, в данной статье подробно рассмотрим приложения для Windows, которые поддерживают работу с KMZ.

Способ 1: Google Earth

После запуска Глобал Маппер выбираем пункт «Open Data File(s)» в меню «File» .

В Проводнике перемещаемся в каталог с искомым объектом, выделяем его и кликаем на кнопку «Открыть» .

Можно еще перетащить файл в окно программы с папки Проводника.

В результате действия загружается информация о местонахождении объекта, которая отображается на карте в виде метки.

Способ 4: ArcGIS Explorer

Приложение является настольной версией геоинформационной платформы ArcGIS Server. KMZ здесь используется для задания координат объекта.

Эксплорер может импортировать формат KMZ по принципу drag-and-drop. Перетаскиваем исходный файл с папки Проводника в область программы.

Открытый файл.

Как показал обзор, все способы открывают формат KMZ. В то время как Google Earth и Global Mapper лишь отображают местонахождение объекта, SketchUp использует KMZ как дополнение к 3D-модели. В случае с ArcGIS Explorer указанное расширение может применяться для точного определения координат инженерных коммуникаций и объектов земляного кадастра.

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.