Chatroom Source

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

while True:
    print('waiting for new connection')
    conn,addr = s.accept()
    print('New connection: ' + str(addr))

    motd = "Welcome to PolyChat!"
    conn.sendto(bytes(motd,'utf-8'), addr)

    char = ''
    message = ''
    while char != None and char != 'q':
        char,temp = conn.recvfrom(1024)
        char = char.decode('utf-8')
        message += char

Platformer Python Code

import turtle, random,time
map = input('Select a map from 1-8 or press 9 for random map')
max = 8
map = int(map)
if map == max:
  map = random.randint(1,max-1)
if map == 1:
  mapName = "v"
if map == 2:
  mapName = "d"
if map == 3:
  mapName = "m"
if map == 4:
  mapName = "a"
if map == 5:
  mapName = "j"
if map == 6:
  mapName = "e (1)"
if map == 7:
  mapName = "t"
if map == 8:
  mapName = "l"

charlist = ['rainbowbob','Kataniguana','yurp','REEE','Zhane','america','lightning','Goku','Symmetra','Dva','Junkrat2','Mercy','soldier']
char1 = int(input('Player 1 Choose a character from the list.'))
char2 = int(input('Player 2 Choose a character from the list.'))
char1 = charlist[char1-1]
char2 = charlist[char2-1]

you = turtle.Turtle()
them = turtle.Turtle()
ball = turtle.Turtle()
screen = turtle.Screen()
screen.setup(400, 400)
direction = "up"
move_speed = 10

def up():
  xold = you.xcor()
  yold = you.ycor()
  if you.ycor()> 200:
def down():
  xold = you.xcor()
  yold = you.ycor()
  if you.ycor()< -200:
def left():
  xold = you.xcor()
  yold = you.ycor()
  if you.xcor()< -200:
def right():
  xold = you.xcor()
  yold = you.ycor()
  if you.xcor()> 200:
def jump():

def up2():
  xold2 = them.xcor()
  yold2 = them.ycor()
  if them.ycor()> 200:
def down2():
  xold2 = them.xcor()
  yold2 = them.ycor()
  if them.ycor()< -200:
def left2():
  xold2 = them.xcor()
  yold2 = them.ycor()
  if them.xcor()< -200:
def right2():
  xold2 = them.xcor()
  yold2 = them.ycor()
  if them.xcor()> 200:
def jump2():
def findbox(xold, yold):
  if map == 1:
    coords = [
  if map == 7:
     coords = [

  sprites = [you, them]
  for i in sprites:
    for j in coords:
      if i.xcor() > j[0] and i.xcor() < j[1]: 
        if i.ycor() > j[2] and i.ycor() < j[3]:
          print('you are in the box')
def fly(ball):
  global direction
  if direction == "up":
  if direction == "down":
  if direction == "left":
  if direction == "right":



screen.onkey(up, "Up")
screen.onkey(down, "Down")
screen.onkey(left, "Left")
screen.onkey(right, "Right")

screen.onkey(up2, "w")
screen.onkey(down2, "s")
screen.onkey(left2, "a")
screen.onkey(right2, "d")

GPS Code for USB Receiver

import serial
gpsPort = "/dev/ttyACM0"
gpsSerial = serial.Serial(gpsPort, baudrate = 9600, timeout = 0.5)

def parseGPS(data):
    gps = data

        if gps[2:8] == "$GNGGA":
            gps = gps.split(",")

            timeHour = (int(gps[1][0:2]) - 4) % 24
            timeMin = int(gps[1][2:4])
            timeSec = int(gps[1][4:6])
            print("Time: " + str(timeHour) + ":" + str(timeMin) + ":" + str(timeSec))

            latDeg = int(gps[2][0:2])
            latMin = int(gps[2][2:4])
            latSec = float(gps[2][5:9]) * (3/500)
            latNS = gps[3]
            print("Latitude:  " + str(latDeg) + "°" + str(latMin) + "'" + str(latSec) + '" ' + latNS)

            longDeg = int(gps[4][0:3])
            longMin = int(gps[4][3:5])
            longSec = float(gps[4][6:10]) * (3/500)
            longEW = gps[5]
            print("Longitude:  " + str(longDeg) + "°" + str(longMin) + "'" + str(longSec) + '" ' + longEW)

            alt = float(gps[9])
            print("Altitude: " + str(alt) + " m")

            sat = int(gps[7])
            print("Satellites: " + str(sat))
        if gps[2:8] == "$GNRMC":
            gps = gps.split(",")

            speed = float(gps[7]) * 1.852
            print("Speed: " + str(speed) + " km/h")
            head = float(gps[8])
            print("Heading: " + str(head))
            gps = ""
    except Exception as error:

    return gps
while True:

Current Combined Code

import os
import picamera
import sense_hat
import time
import yagmail

camera = picamera.PiCamera()
camera.resolution = (1280, 720)
framerate = 5
camera.framerate = framerate
camera.annotate_text_size = 18

senseHat = sense_hat.SenseHat()

gps = "GPS Data"

def annotate():
    timeNow = "Time: " + str(time.strftime("%a %d %b %Y %H:%M:%S", time.localtime()))
    temperatureNow = "Temperature: " + str(round(senseHat.get_temperature())) + " C"
    humidityNow = "Humidity: " + str(round(senseHat.get_humidity())) + "%"
    locationNow = "Location: " +gps
    annotation = timeNow + "\n" + temperatureNow + "\n" + humidityNow + "\n" + locationNow
    return annotation

def getPicture(annotation):
    filename = "/home/pi/Pictures/" + str(time.strftime("%Y-%m-%d@%H:%M:%S", time.localtime())) + ".jpg"

        camera.annotate_text = annotation
    except Exception as error:

    return filename

def getVideo(length):
    filename = "/home/pi/Videos/" + str(time.strftime("%Y-%m-%d@%H:%M:%S", time.localtime())) + ".mp4"

        for index in range(length):
            camera.annotate_text = (annotate())
    except Exception as error:

    os.system("ffmpeg -r " + str(framerate) + " -i /home/pi/testVideo.h264 -vcodec copy " + filename)

    return filename

def sendMail(filename):
    receiver = ["", ""]
    body = "Sent at " + str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + "."

        gmail = yagmail.SMTP("", "password")

            to = receiver,
            subject = "Paul's Balloon",
            contents = body, 
            attachments = filename
    except Exception as error:

    print("Message sent.")


Sending Emails in Python

Sending an email in Python with no attachments.

import smtplib, ssl

smtp_server = ""
port = 587  # For starttls
sender_email = ""
password = input("Type your password and press enter: ")

# Create a secure SSL context
context = ssl.create_default_context()

# Try to log in to server and send email
    server = smtplib.SMTP(smtp_server,port)
    server.ehlo() # Can be omitted
    server.starttls(context=context) # Secure the connection
    server.ehlo() # Can be omitted
    server.login(sender_email, password)
    # TODO: Send email here
except Exception as e:
    # Print any error messages to stdout

Snapping a still image in Python

from picamera import PiCamera
camera = PiCamera()

Raspberry Pi Camera Source


import email, smtplib, ssl

from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

subject = "An email with attachment from Python"
body = "This is an email with attachment sent from Python"
sender_email = ""
receiver_email = ""
password = input("Type your password and press enter:")

# Create a multipart message and set headers
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject
message["Bcc"] = receiver_email  # Recommended for mass emails

# Add body to email
message.attach(MIMEText(body, "plain"))

filename = "document.pdf"  # In same directory as script

# Open PDF file in binary mode
with open(filename, "rb") as attachment:
    # Add file as application/octet-stream
    # Email client can usually download this automatically as attachment
    part = MIMEBase("application", "octet-stream")

# Encode file in ASCII characters to send by email    

# Add header as key/value pair to attachment part
    f"attachment; filename= {filename}",

# Add attachment to message and convert message to string
text = message.as_string()

# Log in to server using secure context and send email
context = ssl.create_default_context()
with smtplib.SMTP_SSL("", 465, context=context) as server:
    server.login(sender_email, password)
    server.sendmail(sender_email, receiver_email, text)


import yagmail

receiver = ""
body = "Hello there from Yagmail"
filename = "document.pdf"

yag = yagmail.SMTP('mygmailusername', 'mygmailpassword')
    subject="Yagmail test with attachment",

pip3 install yagmail 🙂

Scheduling Scripts in CRON

Setting up the Pi to run Python scripts

All right, your Pi is up and running, now you just need to configure it to run Python scripts.
The good news is: there’s not much to do if you are using Raspbian, as it has Python installed out of the box
Screen Shot 2018-09-05 at 18.18.11.pngOne thing you can do is download the latest version, probably because Raspbian does not have the latest release. Head over to, and upgrade if necessary.But other than this you are good to go. You can copy your existing .py files and start using them with the built in IDE or Terminal straight away. Speaking of which: if you are copying over files you used on Windows or OS X, remember that on Linux you’ll need a different shebang line. You probably know where to look this up, but here it is for reference:

  • On Windows, the shebang line is #! python3.
  • On OS X, the shebang line is #! /usr/bin/env python3.
  • On Linux, the shebang line is #! /usr/bin/python3.
    (shebang lines are the first lines in python script files that tells the system where to locate the interpreter)

Also, if you want to start scripts from the terminal there are a few extra steps to do:

  • Place them .py files in your home folder
  • Make them executable with the following command: chmod +x
    Now you can start a script by typing in ./ to the terminal
    (If you place them somewhere else than your home folder you will have to describe the whole path to start them)

Automating scripts on the Pi with CRON

Now to the interesting part. So far we set up our Pi and started to run python scripts on it. But logging in through RealVNC or SSH every time we want a script to run is not really convenient (with the exception if we want to trigger scripts via SSH coming from another device or service automatically, but this will be detailed in another post).
If we have a web-scraping script that looks for some info on the web every day and returns some information (like the food notifier explained in my previous post), then what we want is total automation. The script should start all by it self, do it’s job, and return the information.
Luckily we can do that with a built in tool in Linux called CRON.

How to setup CRON

  • Log into your Pi with realVNC, and start Terminal.
    RPi Terminal.png
  • In the Terminal, enter crontab -e. If you want a command to run with system permissions, use the sudo crontab -e command to open the root account’s crontab file.
  • You might be asked to select an editor. If this happens choose Nano (for me this was the default)
  • You will be presented with the following screen:
    RPi Terminal crontab.png
    Every line that starts with a # is just a comment and will be not executed.
  • Use the arrows or Page Down to scroll down to the bottom of the page
  • Each line you add here will be executed.

The format for the parameters is the following:
Minutes Hours Day of month Month Weekday Command
If you want to skip a parameter, just add * as input.

From the Raspberry Pi Official API:

Scheduling tasks with Cron

Cron is a tool for configuring scheduled tasks on Unix systems. It is used to schedule commands or scripts to run periodically and at fixed intervals. Tasks range from backing up the user’s home folders every day at midnight, to logging CPU information every hour.

The command crontab (cron table) is used to edit the list of scheduled tasks in operation, and is done on a per-user basis; each user (including root) has their own crontab.

Cron GUI

A graphical application for Cron is available by installing the gnome-schedulepackage:

sudo apt-get install gnome-schedule

You can then launch the program Scheduled Tasks from the main menu.

Editing crontab

Run crontab with the -e flag to edit the cron table:

crontab -e

Select an editor

The first time you run crontab you’ll be prompted to select an editor; if you are not sure which one to use, choose nano by pressing Enter.

Add a scheduled task

The layout for a cron entry is made up of six components: minute, hour, day of month, month of year, day of week, and the command to be executed.

# m h  dom mon dow   command
# * * * * *  command to execute
# ┬ ┬ ┬ ┬ ┬
# │ │ │ │ │
# │ │ │ │ │
# │ │ │ │ └───── day of week (0 - 7) (0 to 6 are Sunday to Saturday, or use names; 7 is Sunday, the same as 0)
# │ │ │ └────────── month (1 - 12)
# │ │ └─────────────── day of month (1 - 31)
# │ └──────────────────── hour (0 - 23)
# └───────────────────────── min (0 - 59)

For example:

0 0 * * *  /home/pi/

This cron entry would run the script every day at midnight.

View scheduled tasks

View your currently saved scheduled tasks with:

crontab -l

Run a task on reboot

To run a command every time the Raspberry Pi starts up, write @reboot instead of the time and date. For example:

@reboot python /home/pi/

This will run your Python script every time the Raspberry Pi reboots. If you want your command to be run in the background while the Raspberry Pi continues starting up, add a space and & at the end of the line, like this:

@reboot python /home/pi/ &

Raspbian API


KML Guide

KML Tutorial

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 KML file 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.

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.


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: simplefloating, and extruded. The KML code for the simple placemark looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="">
    <name>Simple placemark</name>
    <description>Attached to the ground. Intelligently places itself 
       at the height of the underlying terrain.</description>

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:
    • name that is used as the label for the Placemark
    • description that appears in the “balloon” attached to the Placemark
    • 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 paste the “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 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, the angle brackets need to be written as entity references to prevent Google Earth from parsing the HTML incorrectly (for example, the symbol > is written as &gt; and the symbol < is written as &lt;). This is a standard feature 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:

<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="">
      <name>CDATA example</name>
          <h1>CDATA Tags are useful!</h1>
          <p><font color="red">Text is <i>more readable</i> and 
          <b>easier to write</b> when you can avoid using entity 

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

<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="">
      <name>Entity references example</name>
	        &lt;h1&gt;Entity references are hard to type!&lt;/h1&gt;
	        &lt;p&gt;&lt;font color="green"&gt;Text is 
          &lt;i&gt;more readable&lt;/i&gt; 
          and &lt;b&gt;easier to write&lt;/b&gt; 
          when you can avoid using entity references.&lt;/font&gt;&lt;/p&gt;

Ground Overlays

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

<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="">
    <name>Ground Overlays</name>
    <description>Examples of ground overlays</description>
      <name>Large-scale overlay on terrain</name>
      <description>Overlay shows Mount Etna erupting 
          on July 13th, 2001.</description>

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

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, and east and west longitudes. In addition, rotation values are given for images 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.


Many different types of paths can be created in Google Earth, 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:

<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="">
    <description>Examples of paths. Note that the tessellate tag is by default
      set to 0. If you want to create tessellated lines, they must be authored
      (or edited) directly in KML.</description>
    <Style id="yellowLineGreenPoly">
      <name>Absolute Extruded</name>
      <description>Transparent green wall with yellow outlines</description>
        <coordinates> -112.2550785337791,36.07954952145647,2357

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


You can use Polygons to create simple buildings and other shapes. Check out the Polygons folder in the KML Samplesfile 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 :

<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="">
    <name>The Pentagon</name>

2 Advanced KML Documents

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):

<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="">
    <Style id="transBluePoly">
      <name>Building 41</name>
            <coordinates> -122.0857412771483,37.42227033155257,17

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.”
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="">
    <name>Highlighted Icon</name>
    <description>Place your mouse over the icon to see it display the new icon</description>
    <Style id="highlightPlacemark">
    <Style id="normalPlacemark">
    <StyleMap id="exampleStyleMap">
      <name>Roll over this icon</name>

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 Overlays folder in the KML Samples file.

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

<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="">
    <name>Absolute Positioning: Top left</name>
    <overlayXY x="0" y="1" xunits="fraction" yunits="fraction"/>
    <screenXY x="0" y="1" xunits="fraction" yunits="fraction"/>
    <rotationXY x="0" y="0" xunits="fraction" yunits="fraction"/>
    <size x="0" y="0" xunits="fraction" yunits="fraction"/>

Positioning is controlled by mapping a point in the image specified by <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 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 KML 2.2 Reference.

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.

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 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/

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


import random

latitude = random.randrange(-90, 90)
longitude = random.randrange(-180, 180)
kml = (
   '<?xml version="1.0" encoding="UTF-8"?>\n'
   '<kml xmlns="">\n'
   '<name>Random Placemark</name>\n'
   ) %(longitude, latitude)
print 'Content-Type: application/\n'
print kml

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

<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="">
    <name>Network Links</name>
    <description>Network link example 1</description>
      <name>Random Placemark</name>
      <description>A simple server-side script that generates a new random
        placemark on each call</description>

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 <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):

GET /path/to/sever/script/query?BBOX=[longitude_west, latitude_south, longitude_east, latitude_north] 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.


import cgi

url = cgi.FieldStorage()
bbox = url['BBOX'].value
bbox = bbox.split(',')
west = float(bbox[0])
south = float(bbox[1])
east = float(bbox[2])
north = float(bbox[3])

center_lng = ((east - west) / 2) + west
center_lat = ((north - south) / 2) + south

kml = ( 
   '<?xml version="1.0" encoding="UTF-8"?>\n'
   '<kml xmlns="">\n'
   '<name>View-centered placemark</name>\n'
   ) %(center_lng, center_lat)

print 'Content-Type: application/\n'
print kml

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

<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="">
    <name>Network Links</name>
    <description>Network link example 2</description>
      <name>View Centered Placemark</name>
      <description>The view-based refresh allows the remote server to calculate
         the center of your screen and return a placemark.</description>

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/

The MIME type for KMZ files is

  • application/

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

  • AddType application/ .kml
  • AddType application/ .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 (<?xml version="1.0" encoding="UTF-8"?>). 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 Developer’s Guide, which describes key KML features. Also, browse the KML Reference for information on specific elements.


Python GPS NMEA Statement Parsing Code in Need of Serious Debugging

import serial
port = "/dev/ttyS0"
def parseGPS(data):
#    print "raw:", data #prints raw data
    if data[0:6] == "$GPRMC":
        sdata = data.split(",")
        if sdata[2] == 'V':
            print("no satellite data available")
        print( "---Parsing GPRMC---",
        time = sdata[1][0:2] + ":" + sdata[1][2:4] + ":" + sdata[1][4:6]
        lat = decode(sdata[3]) #latitude
        dirLat = sdata[4]      #latitude direction N/S
        lon = decode(sdata[5]) #longitute
        dirLon = sdata[6]      #longitude direction E/W
        speed = sdata[7]       #Speed in knots
        trCourse = sdata[8]    #True course
        date = sdata[9][0:2] + "/" + sdata[9][2:4] + "/" + sdata[9][4:6]#date
        print "time : %s, latitude : %s(%s), longitude : %s(%s), speed : %s, True Course : %s, Date : %s" %  (time,lat,dirLat,lon,dirLon,speed,trCourse,date)
def decode(coord):
    #Converts DDDMM.MMMMM &gt; DD deg MM.MMMMM min
    x = coord.split(".")
    head = x[0]
    tail = x[1]
    deg = head[0:-2]
    min = head[-2:]
    return deg + " deg " + min + "." + tail + " min"
print "Receiving GPS data"
ser = serial.Serial(port, baudrate = 9600, timeout = 0.5)
while True:
   data = ser.readline()


Running a C Program from Python

import subprocess
cmd = "nameOfCProgram.c"
# Example
# cmd = HelloWorld.c
print ("Hey this is Python Script Running\n")["gcc",cmd]) #For Compiling"./a.out") 
#end thats all

The C Code

// HelloWorld.c


int main()
printf("Hello World\n");
printf("This C program Running\n");
return 0;

Koch’s Snowflake in Python

# Draw a Koch snowflake
from turtle import *

def koch(a, order):
    if order > 0:
        for t in [60, -120, 60, 0]:

# Test
koch(100, 0)
koch(100, 1)

Now, we make a small change to the function koch:

    for t in [60, -120, 60, 0]:
            koch(a/3, order-1)

Completed code:

# Choose colours and size
color("sky blue", "white")
size = 400
order = 0

# Ensure snowflake is centred

# Make it fast


# Three Koch curves
for i in range(3):
    koch(size, order)


# Make the last parts appear