O'Reilly Hacks
oreilly.comO'Reilly NetworkSafari BookshelfConferences Sign In/My Account | View Cart   
Book List Learning Lab PDFs O'Reilly Gear Newsletters Press Room Jobs  


 
Buy the book!
Yahoo! Hacks
By Paul Bausch
October 2005
More Info

HACK
#91
Plot Multiple Points on Your Own Map
Use the Yahoo! Maps Web Service to plot several locations on a map at once
The Code
[Discuss (0) | Link to this hack]

The Code

This script accepts a filename for a CSV file and uses the data in the file to create a geo-aware RSS 2.0 file. You won't need any extra modules, so you can simply save the following code to a file called csv_to_geoRSS.pl:

	#!/usr/bin/perl
	# csv_to_geoRSS.pl
	# Converts a CSV file with addresses to geo-aware RSS
	# Usage: csv_to_geoRSS.pl <CSV File>

	use strict;

	# Open the incoming file
	open(CSV, "<@ARGV" ) or die "Can't open @ARGV : $!";

	# Change the .csv extension to .xml for RSS file
	my $RSSfile = $ARGV[0];
	$RSSfile =~ s!csv$!xml!;

	# Open the RSS file for writing
	open(RSS, ">$RSSfile") or die "Can't open file: $!";

	print RSS<<"HEADER_END";
	<?xml version="1.0"?>
	<rss version="2.0" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#"
			xmlns:ymaps="http://api.maps.yahoo.com/Maps/V1/AnnotatedMaps.xsd"> 
	<channel> 
	HEADER_END

	# Loop through the CSV file, adding items
	while(<CSV>) {
		chomp;
		my($address, $city, $state, $zip, $notes) = split(/,/, $_);

	print RSS<<"ITEM_END";
	  <item>
		<title>$address</title>
		<link />
		<description>$notes</description>
		<ymaps:Address>$address</ymaps:Address>
		<ymaps:CityState>$city, $state</ymaps:CityState>
		<ymaps:Zip>$zip</ymaps:Zip>
		<ymaps:Country>us</ymaps:Country>
	</item>
ITEM_END
}
	# Finish the RSS
	print RSS "</channel>\n";
	print RSS "</rss>";

	# Close the files
	close CSV;
	close RSS;

As you look through the script, you can see that the RSS format contains the standard <title>, <link>, and <description> tags. It also has some Yahoo!-specific extension tags including <ymaps:Address>, <ymaps:CityState>, <ymaps:Zip>, and <ymaps:Country>. Because the garage sales in this example don't have titles or links, the address is used as a title and the link tags are blank in the final RSS file. You could easily add more columns to the spreadsheet to hold titles or links.

Also keep in mind that if your source spreadsheet file data contains commas (in the address or note columns, for example), you may need to adjust the script to accommodate. Try saving the spreadsheet as a tab-delimited file and changing the line in the code that separates data by commas so that it instead separates data by tabs:

my($address, $city, $state, $zip, $notes) = split(/\t/, $_);

This measure should help ensure your data lines up properly in the RSS file.


O'Reilly Home | Privacy Policy

© 2007 O'Reilly Media, Inc.
Website: | Customer Service: | Book issues:

All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.