Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-6 of 6 total  RSS 

jQuery Maps Interface - Easily create Google or Yahoo maps

/* jQuery Maps (jmaps) - A jQuery plugin for Google Maps API
* Author: Tane Piper (digitalspaghetti@gmail.com)
* With special thanks Dave Cardwell (who helped on getting the first version of this plugin to work).
* Website: http://code.google.com/p/gmapp/
* Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
* This plugin is not affiliated with Google or Yahoo.
* For Google Maps API and T&C see http://www.google.com/apis/maps/
* For Yahoo! Maps API and T&C see http://developer.yahoo.com/maps/
*
* === Changelog ===
* Version 1.3
* Added support for creating Yahoo! Maps, can create Map, Satallite or Hybrid. Check out available options below
* Added support for creating points on Yahoo! maps.
* Added support for creating Polylines on Yahoo! maps.
* Added support for GeoRSS files on both Yahoo! and Google maps, as well as existing KML support for Google, method
* name was changed from .addKml to .addRss
* Moved directions search out of main namespace, now function that is called from within plugin by providing fields
*
* Version 1.2 (25/07/2007)
* Moved GClientGeocoder into searchAddress method
* Fixed bug in searchAddress method regarding getPoint().
*
* Version 1.1 (16/07/2007)
* Changed name to remove Google from main name - namespace now .jmap.
* Added additional options:
* + Add map dragging enable/disable.
* + Add scroll wheel zooming.
* + Add smooth continuous zooming (on certain browsers).
* + Added clean unloading of Google objects.
* Added .addPoly method. Allows the creation of polylines on the map.
* Added .addKml support for rendering KML Files.
* Added .directions Driving Direction support.
*
* Version 1.0 (13/07/2007)
* Initial version.
* Creates Google Map.
* Add points to map.
* Takes address or postcode, Geocodes and centers map. Also creates a draggable marker.
*/


(function($) {
	/* function searchAddress(jmap, address, settings)
	 * This function is an internal plugin method that returns a GLatLng that can be passed
	 * to a Google map.
	 */
	function searchAddress(jmap, address, settings) {
		
		if (jmap._mapType) {
			alert('Yahoo Maps Geocoding not yet supported');
		}
		
		if (jmap.i.Au) {
			GGeocoder = new GClientGeocoder();
			GGeocoder.getLatLng(address, function(point){
				if (!point) {
					alert(address + " not found");
				} else {
					jmap.setCenter(point,settings.zoom);
					var marker = new GMarker(point, {draggable: true});
					jmap.addOverlay(marker);
					pointlocation = marker.getPoint();
					marker.openInfoWindowHtml("Latitude: " + pointlocation.lat() + "<br />Longitude: " + pointlocation.lng());
					GEvent.addListener(marker, "dragend", function(){
						mylocation = marker.getPoint();
						marker.openInfoWindowHtml("Latitude: " + pointlocation.lat() + "<br />Longitude: " + pointlocation.lng());			
					});
				}
			});
		}	
	}
	
	/* directions: function(map,query, panel)
	 * Takes a Direction query and returns directions for map.  Optional panel for text information
	 */
	function searchDirections(jmap,query,panel) {
		// Yahoo Maps
		if (jmap._mapType) {
			alert('Yahoo Directions support not yet added')	;
		}
		
		// Google Maps
		if (jmap.i.Au) {
			var dirpanel = document.getElementById(panel);
			directions = new GDirections(jmap, dirpanel);
			directions.load(query);
		}
	}

	$.fn.extend({
	/* jmap: function(settings)
	 * The constructor method
	 * Example: $().jmap();
	 */
	jmap: function(settings) {
		var version = "1.3";
		/* Default Settings*/	
		var settings = jQuery.extend({
			provider: "google",		// can be "google" or "yahoo"
			maptype: "hybrid",		// can be "map", "sat" or "hybrid"
			center: [55.958858,-3.162302],	// G + Y
			zoom: 12,				// G + Y
			controlsize: "small",	// G + Y
			showtype: true,			// G + Y
			showzoom: true,			// Y
			showpan: true,			// Y
			showoverview: true,		// G
			showscale: true,		// Y
			dragging: true,			// G + Y
			scrollzoom: true,		// G + Y
			smoothzoom: true,		// G
			searchfield: "#Address",
			searchbutton: "#findaddress",
			directionsto: "#to",
			directionsfrom: "#from",
			directionsfind: "#getDirections",
			directionspanel: "myDirections"
		},settings);
		
		return this.each(function(){
			switch(settings.provider)
			{
				case "yahoo":
					var jmap = this.jMap = new YMap(this);
					switch(settings.maptype) {
						case "map":
							var loadmap = YAHOO_MAP_REG;
							break;
						case "sat":
							var loadmap = YAHOO_MAP_SAT;
							break;
						default:
							var loadmap = YAHOO_MAP_HYB;
							break;
					}
					jmap.setMapType(loadmap);
					jmap.drawZoomAndCenter(new YGeoPoint(settings.center[0],settings.center[1]), settings.zoom);
					if (settings.showtype == true){
						jmap.addTypeControl();	// Type of map Control
					}
					if (settings.showzoom == true && settings.controlsize == "small" ){
						jmap.addZoomShort();	// Small zoom control
					}
					if (settings.showzoom == true && settings.controlsize == "large" ){
						jmap.addZoomLong();		// Large zoom control
					}
					if (settings.showpan == true) {
						jmap.addPanControl();	// Pan control
					}
					if (settings.showscale == false) {
						/* On by default */
						jmap.removeZoomScale();	// Show scale bars
					}
					if (settings.dragging == false) {
						/* On by default */
						jmap.disableDragMap();	// Is map draggable?
					}
					if (settings.scrollzoom == false) {
						/* On by default */
						jmap.disableKeyControls(); // Mousewheel and Keyboard control
					}
					break;
					
				case "mslive":
					alert('Microsoft Live Maps are currently not supported but planned for version 1.4')
					break;
					
				default:	
					var jmap = this.jMap = new GMap2(this);
					switch(settings.maptype) {
						case "map":
							var loadmap = G_NORMAL_MAP;
							break;
						case "sat":
							var loadmap = G_SATELLITE_MAP;
							break;
						default:
							var loadmap = G_HYBRID_MAP;
							break;
					}
					jmap.setCenter(new GLatLng(settings.center[0],settings.center[1]),settings.zoom,loadmap);
					switch(settings.controlsize)
					{
						case "small":
							jmap.addControl(new GSmallMapControl());
							break;
						case "large":
							jmap.addControl(new GLargeMapControl());
							break;
						case "none":
							break;
						default:
							jmap.addControl(new GSmallMapControl());
					}
					if (settings.showtype == true){
						jmap.addControl(new GMapTypeControl());
					}
					if (settings.showoverview == true){
						jmap.addControl(new GOverviewMapControl());
					}
					if (settings.scrollzoom == true) {
						/* Off by default */
						jmap.enableScrollWheelZoom();
					}
					if (settings.smoothzoom == true) {
						/* Off by default*/
						jmap.enableContinuousZoom();
					}
					if (settings.dragging == false) {
						/* On by default */
						jmap.disableDragging();
					}
			}	
			/* Seach for the lat & lng of our address*/
			jQuery(settings.searchbutton).bind('click', function(){
				searchAddress(jmap, jQuery(settings.searchfield).attr('value'), settings);
			});
			/* Search for Directions */
			jQuery(settings.directionsfind).bind("click", function(){
				var from = $(settings.directionsfrom).attr('value');
				var to = $(settings.directionsto).attr('value');
				searchDirections(jmap, "from: " + from + " to: " + to, settings.directionspanel);	
				$(settings.directionsfrom).attr('value', to);
				$(settings.directionsto).attr('value', '');
				return false;
			});
			/* On document unload, clean unload Google API*/
			jQuery(document).unload(function(){ GUnload(); });
		});
		},
	/* myMap: function()
	 * Returns a map object from the API, so it's available to the user
	 * Example: $().myMap().setCenter(...) for Google;
	 * Example: $().myMap().drawZoomAndCenter(...) for Yahoo;
	 */
	myMap: function() {
		return this[0].jMap;	
	},
	/* addPoint: function()
	 * Returns a marker to be overlayed on the Google map
	 * Example: $().addPoint(...);
	 */
	addPoint: function(pointlat, pointlng, pointhtml, isdraggable, removable) {
		var jmap = this[0].jMap;
		// Yahoo Maps
		if (jmap._mapType) {			
			var marker = new YMarker(new YGeoPoint(pointlat, pointlng));	// Create the Yahoo marker type
			YEvent.Capture(marker, EventsList.MouseClick, function(){		// Add mouseclick to open HTML
				marker.openSmartWindow(pointhtml);
			});
			// Below code does not work as expected
			/*if (removable == true) {
				YEvent.Capture(marker, EventsList.MouseDoubleClick, function(){
					jmap.removeOverlay(marker);
				});
			}*/
			jmap.addOverlay(marker);	// Add marker to map
		}
		
		// Google Maps	
		if (jmap.i.Au) {
			var marker = new GMarker(new GLatLng(pointlat,pointlng), { draggable: isdraggable } );
			GEvent.addListener(marker, "click", function(){
				marker.openInfoWindowHtml(pointhtml);
			});
			if (removable == true) {
				GEvent.addListener(marker, "dblclick", function(){
					return jmap.removeOverlay(marker);
				});
			}
			return jmap.addOverlay(marker);
		}
	},
	/* addPoly: function(poly)
	 * Takes an array of GLatLng points, converts it to a vector Polyline to display on the map
	 * Example: $().addPoly(...);
	 */
	addPoly: function (poly, colour, width, alpha) {
		var jmap = this[0].jMap;
		// Yahoo Maps
		if (jmap._mapType) {
			return	jmap.addOverlay(poly, colour, width, alpha);
		}
		// Google Maps
		if (jmap.i.Au) {
			return jmap.addOverlay(poly);
		}
	},
	/* addRss: function()
	 * Takes a KML file and renders it to the map.
	 * Example: $().addPoint(...);
	 */
	addRss: function (rssfile) {
		var jmap = this[0].jMap;
		// Yahoo Maps
		if (jmap._mapType) {
			var geoXml = new YGeoRSS(rssfile);
			return jmap.addOverlay(geoXml);
		}
		// Google Maps
		if (jmap.i.Au) {
			var geoXml = new GGeoXml(rssfile);
			return jmap.addOverlay(geoXml);
		}
		
	}
});
})(jQuery);

Get Google maps informations (distance and time, French version)

Here a little script to get time and distance between two towns with google maps. You can change "voiture" by your langage word "car", or anything else.

this is a command line version : # ruby myscript.rb "Lyon" "Paris"
You can easily change it for a Ruby on Rails project :)
Maybie we can upgrade this script using regexp.

require "open-uri"
require "cgi"

# Command line arguments ... 
$*.each {|argu| argu.gsub!("\"","")}
# Defaults towns
src = "Lyon"
dest = "Paris"
# If we have fill two aguments ...
if $*.size == 2 then
        src = $*[0]
        dest = $*[1]
end

html = ""
url = "http://maps.google.com/maps?f=d&hl=fr&saddr=" + CGI.escape(src) + "&daddr="+ CGI.escape(dest)
# Read the html page
open(url) {|f|
        f.each_line {|line| html += line}
}
pos1 = html.index("voiture") # French version
pos2 = html.index("</td>",pos1) unless pos1 == nil
pos1 = html.index(">",pos2+6)+1 unless pos2 == nil
pos2 = html.index("</td>",pos2+1) -1 unless pos2 == nil
ret = ""
if pos1 != nil and pos2 != nil
        ret = html[pos1..pos2].gsub!("&#160;", " ")
else
        ret = "0"
end
html = nil
p ret

IP Location on Google Maps

/*
Example of usage:
$ ./lip.rb snippets.dzone.com
. Hostname: snippets.dzone.com
. Country Code: US
. Country Name: United States
. Region: CA
. Region Name: California
. City: Los Angeles
. Postal Code: 90017
. Latitude: 34.0530
. Longitude: -118.2642
. ISP: CoreExpress
. Organization: CoreExpress
. Metro Code: 803
. Area Code: 213
. Google Maps URL: http://maps.google.com/maps?q=34.0530,+-118.2642&iwloc=A&hl=en
*/

#!/usr/bin/env ruby -w

if ARGV.empty?
  puts <<-T
Locate IP by haqu
usage: ./lip.rb ip|domain ...
  T
  exit
end

require 'net/http'
require 'uri'

uri = URI.parse('http://www.maxmind.com/app/locate_ip')
res = Net::HTTP.post_form(uri,
  { 'ips' => ARGV.join(' '),
    'type' => '', 'u' => '', 'p' => ''
  } )
fstr = res.body

fstr.gsub!("Edition Results<\/span><p>","CHECKPOINT")
fstr =~ /CHECKPOINT(.+?)<\/table>/m
fields = $1.grep(/<(th|td)>/)
fields.each do |f|
  f.strip!
  f.gsub!(/<[^>]+>/,"")
end

(0...13).each do |i|
  puts ". #{fields[i]}: #{fields[i+13]}"
end

maplink = "http://maps.google.com/maps?q=#{fields[20]},+#{fields[21]}&iwloc=A&hl=en"
puts ". Google Maps URL: #{maplink}"

Numeric colums for latitude / longitude in Rails 1.2 migrations

In Rails 1.1.6, "numeric" datatypes didn't work in migrations. This confused a lot of people who wanted to store geographic data (latitude and longitude) for use in Google Maps and the like. Floats worked, but their precision is limited -- you'll lose three or more decimal places of precision if you store the results of a typical geocoding call in a Float column. And don't even think about using strings to store your latitudes/longitudes.

Fortunately, the numeric datatype problem is fixed in Rails 1.2, and you can now have do this in your migrations:

class CreatePlaces < ActiveRecord::Migration
  def self.up
    create_table :places do |t|
      t.column "lat", :decimal, :precision => 15, :scale => 10
      t.column "lng", :decimal, :precision => 15, :scale => 10
    end
  end

  def self.down
    drop_table :places
  end
end


FYI, if you're stuck on Rails 1.1.6, you can use this approach:
class CreatePlaces < ActiveRecord::Migration
  def self.up
    create_table :places do |t|
      t.column :lat, :float 
      t.column :lng, :float
    end
    execute("ALTER TABLE places MODIFY lat numeric(15,10);")
    execute("ALTER TABLE places MODIFY lng numeric(15,10);")
  end

  def self.down
    drop_table :places
  end
end

... but that's ugly, database-specific (works on MySQL), and not very DRY.

Draggable eInsert

// description of your code here

<script type="text/javascript">
    //<![CDATA[
    
    if (GBrowserIsCompatible()) { 

      var map = new GMap2(document.getElementById("map"));
      map.addControl(new GLargeMapControl());
      map.addControl(new GMapTypeControl());
      map.setCenter(new GLatLng(53.849, -3.022),16);

      // Optionally set the cursors to be used for dragging
      GDraggableObject.setDraggableCursor("move");


      // Insert the "Nosuch Road" road 
      var insert1 = new EInsert(new GLatLng(53.85022, -3.01772), "nosuch.png", new GSize(145,233), 16);
      map.addOverlay(insert1);
      // Make it draggable
      insert1.makeDraggable();
      
      // A new event that returns the new latlng when the drag ends
      GEvent.addListener(insert1, "dragend", function (pt) {
        GLog.write("New position of insert = "+ pt.lat() + ","+pt.lng());
      });

    }

    //]]>
    </script>

Using Google Maps EZ

Chris Houser writes an easy HTML API for Google Maps.
Here's the simplest example
<html>
<head>
  <script src="http://maps.google.com/maps?file=api&v=1&key=yourgmapskey"></script>
  <script src="http://bluweb.com/chouser/gmapez/gmapez.js"></script>
</head>
<body>

  <div class="GMapEZ" style="width: 300px; height: 300px;"></div>

</body>
</html>

See more examples here
http://bluweb.com/us/chouser/gmapez/docs.html
« Newer Snippets
Older Snippets »
Showing 1-6 of 6 total  RSS