Kml To Wkt Converter To Mp3 Average ratng: 3,5/5 3807 reviews

If you have geometry as WKT or WKB, use wkt or wkt name for the geometry column name. Notice to KML format - KML converter strictly transforms input dataset to WGS 84 coordinate reference system (if needed). Please make sure that coordinate reference system of your input dataset is assigned correctly - otherwise the resulting KML file may be.

wkt2kml.py
#!/usr/bin/env python
# coding=utf-8
importsys
importre
importsimplekml
importargparse
importrandom
defsplitByLines(wkt):
returnre.findall(r'LINESTRING(([^)]*)', wkt)
defgetAColor():
r=lambda: random.randint(0,255)
r()
return'#FF{:02X}{:02X}{:02X}'.format(r(),r(),r())
defcreateKMLLines(lines, colors):
kml=simplekml.Kml()
foridx,linenumerate(lines):
splitted=re.findall(r'[^ ,]+', l)
spl= [float(i) foriinsplitted]
coords=zip(splitted[::2],splitted[1::2])
ls=kml.newlinestring(name='Line '+str(idx))
ls.coords=coords
ifcolors:
ls.style.linestyle.color=getAColor()
ls.style.linestyle.width=4
returnkml
# Argument Parser
parser=argparse.ArgumentParser(description='Converter of WKT's linestrings to KML')
parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),default=sys.stdin)
parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),default=sys.stdout)
parser.add_argument('-c','--colors', action='store_true', help='add random colors to the lines for easy differentiation')
args=parser.parse_args()
wkt=args.infile.read()
lines=splitByLines(wkt)
kml=createKMLLines(lines, args.colors)
args.outfile.write(kml.kml())
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

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 KML Reference. 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 (SamplesInEarth) 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.

All of the examples described here are in the KML Samples file. Begin by downloading that file to view the examples in Google Earth.

For More Information

The KML 2.2 Reference provides details about the KMLfile format. If you're familiar with XML, you will also be interested in the KML 2.2 Schema.

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

  • Basic KML Documents
  • Advanced KML Documents

The simplest kind of KML documents are those that can be authoreddirectly in Google Earth—that is, you don't need to edit or createany KML in a text editor. Placemarks, ground overlays, paths, andpolygons 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 <Point> 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.

Open the KML Samples file in Google Earth and expand the Placemarks subfolder. This folder includes three different types of placemark: simple, floating, and extruded. The KML code for the simple placemark looks like this:

The structure of this file breaks down as follows:

  • An XML header. This is line 1 in every KML file. No spaces or other characters can appear before this line.
  • A KML namespace declaration. This is line 2 in every KML 2.2 file.
  • A Placemark object that contains the following elements:
    • A name that is used as the label for the Placemark
    • A description that appears in the 'balloon' attached to the Placemark
    • A Point that specifies the position of the Placemark on the Earth's surface (longitude, latitude, and optional altitude)

If you were wondering where the Placemark is, it's right over Google's Building 41, where we developed Google Earth!

What users commonly think of as a 'placemark' in Google Earth is actually a <Placemark> element with a <Point> child in KML. A Point Placemark is the only way to draw an icon and label in the 3D Viewer of Google Earth. By default, the icon is the familiar yellow pushpin. In KML, a <Placemark> can contain one or more geometry elements, such as a LineString, Polygon, or Model. But only a <Placemark> with a Point can have an icon and label. The Point is used to place the icon, but there is no graphical representation of the Point itself.

Descriptive HTML in Placemarks

The KML Samples file has an example of almost everything you can do with Placemark text. You can add links, font sizes, styles, and colors, and specify text alignment and tables. If you'd like to see the full list, copy and pastethe 'Descriptive HTML' Placemark example (in the Styles and Markup folder) into a text editor.

Auto-Markup in Google Earth (Release 4.0 and later)

Google Earth 4.0 has an auto-markup feature that automatically converts text such as www.google.com into active hyperlinks that the user can click. Text inside the <description> tag, the <Snippet> tag, and the <text> element of <BalloonStyle> are all automatically transformed into standard HTTP hyperlinks. You don't need to add the <a href= ..> tags yourself.

Using the CDATA Element

If you want to write standard HTML inside a <description> tag, you can put it inside a CDATA tag. If you don't, theangle brackets need to be written as entity references to preventGoogle Earth from parsing the HTML incorrectly (for example, the symbol > is written as &gt; and the symbol < is written as &lt;). This is a standardfeature of XML and is not unique to Google Earth.

Consider the difference between HTML markup with CDATA tags and without CDATA. First, here's the <description> with CDATA tags:

And here's the <description> without CDATA tags, so that special characters must use entity references:

Ground Overlays

Ground overlays enable you to 'drape' an image onto the Earth's terrain. The <Icon> element contains the link to the .jpg file with the overlay image. Here is the example ground overlay in the KML Samples file, which shows Mount Etna erupting in 2001:

Notice that the file begins with the same two lines as the first example: the XML header and KML namespacedeclaration.

This example uses a Folder (titled 'Ground Overlays') as a mechanism to group and label its contents. Notice how the Folder appears in the Places panel when you load the KML Samples file into Google Earth.

The positioning of a ground overlay is controlled by the <LatLonBox> tag. Bounding values are given for the north and south latitudes, andeast and west longitudes. In addition, rotation values are given forimages whose y-axis doesn't coincide with grid north. This example uses a JPEG image for the overlay. Google Earth also supports BMP, GIF, TIFF, TGA, and PNG formats.

Paths

Many different types of paths can be created in GoogleEarth, and it is easy to be very creative with your data. In KML, a path is created by a <LineString> element. Take a look at the 'Absolute Extruded' example in the Paths folder and you can see how the shape has been generated by the following code:

Notice how it is really just one line drawn at altitude above theground. The <tessellate> tag breaks the line up into smaller chunks, andthe <extrude> tag extends the line down to the ground.

Polygons

You can use Polygons to create simple buildings and other shapes. Check out the Polygons folder in the KML Samples file for examples.

The Pentagon example is generated by drawing simple inner and outer shells and then extruding them down to the ground. Here is the code :

This section describes some of the KML elements that must be authored using a text editor, such as shared styles for geometry, highlighted icons for Placemarks, and screen overlays. Authoring KML 'by hand' is a bit more advanced than using the Google Earth interface to create and modify features, but with a small amount of practice, most users are comfortable editing KML files to add these effects.

Styles for Geometry

Once you've created features within Google Earth and examined the KML code Google Earth generates, you'll notice how styles are an important part of how your data is displayed. Power users will want to learn how to define their own styles.

If you define a Style at the beginning of a KML Document and also define an ID for it, you can use this style in Geometry, Placemarks, and Overlays that are defined elsewhere in the Document. Because more than one element can use the same Style, styles defined and used in this way are referred to as shared styles. You define a given Style once, and then you can reference it multiple times, using the <styleUrl> element. If the Style definition is within the same file, precede the Style ID with a # sign. If the Style definition is in an external file, include the complete URL in the <styleUrl> element.

The KML Samples file contains a number of shared styles, each defined with an ID at the beginning of the file. Note that it's easiest if your IDs are descriptive strings so that you can easily tell what their effect is. Here's an example of a style ('transBluePoly') that defines a transparent blue color for the polygon faces and a line width of 1.5 (and default color of white) for the edges of the polygon. This style is used by Building 41 in the Google Campus example (in the Polygons folder):

Note that the <styleUrl> element is a child of <Placemark> (not of the Geometry it affects).

Styles for Highlighted Icons

The 'Highlighted Icon ' in the Styles and Markup folder shows you how to create a roll-over effect with KML. The Document defines two styles, one for the 'normalPlacemark' and one for the 'highlightPlacemark' (shown when the cursor rolls over the Icon). The <StyleMap> element has two key/value pairs that map each icon style to an icon state. There are two icon states: normal and highlight.

The basic steps shown here are as follows:

  1. Define a <Style> for the Placemark's normal icon, and assign an ID to it (here, 'normal Placemark'). The <Style> includes an <Icon> with an <href> to the actual image to use, as shown below.
  2. Define a <Style> for the Placemark's highlight icon and assign an ID to it (here, 'highlightPlacemark').
  3. Create the <StyleMap> element and assign an ID to it ('exampleStyleMap'). The Placemark will refer to this ID.
  4. In the <StyleMap> element, specify '#normalPlacemark' for the normal state.
  5. In the <StyleMap> element, specify '#highlightPlacemark' for the highlight state.
  6. In the Placemark, add a <styleUrl> element that refers to '#exampleStyleMap.'

Screen Overlays

Screen overlays cannot be authored directly within Google Earth and are thus more difficult to create than ground overlays. A comprehensive collection of samples is included in the Screen Overlaysfolder in the KML Samples file.

As an example, enable the 'AbsolutePositioning: Top left' folder in the KML Samples file and you will see a screen overlay at thetop left of the view window. This was created with the following KMLcode:

Positioning is controlled by mapping a point in the image specifiedby <overlayXY> to a point on the screen specified by<screenXY>. 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 toobtain other fixed positions, and to create images that sizedynamically with screen size. (Note that xunits and yunits can also bespecified as 'pixels' for precision control.) For further detail, see the KML 2.2 Reference.

Network Links

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

Or listen to our entire catalogue with our high-quality unlimited streaming subscriptions. Zero DRMThe downloaded files belong to you, without any usage limit. Tez cadey seve download.

The <href> 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 <Model> 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 <href> can point to data that is dynamically generated—for example, by a CGI script located on a network server. With some knowledge of a scriptinglanguage 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 typeto 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 theserver's error as the text for a folder name. For example, you couldhave the server return <Folder><name>database inaccessible</name></Folder> 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 <coordinates> element of a <Point>. Whenever the network link is refreshed, the Python script runs again and generates KML with new latitude and longitude values.

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

View-Based Refresh Queries

A standard network link is a uni-directional link: data flows onlyfrom the server to Google Earth. The view-based refresh enablesbi-directional communication. When the view-based refresh is active,Google Earth returns the view coordinates to the server at a specifiedtime. This may be every n seconds, minutes, or hours, or once a certainamount of time has elapsed since the view stopped moving. See <viewRefreshMode> 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):

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

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 returnmessage 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.

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

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.

When responding to a request from Google Earth (or any Earth browser), a KMLserver must follow a certain set of rules so that Google Earth cancorrectly 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.

Thebody of the response must contain valid KML data, including the XML declaration (<?xml version='1.0' encoding='UTF-8'?>). Ifthe server returns invalid KML, the Network Link will stop, deactivate,and output an error message.

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