giovedì 15 aprile 2010

Simple maps with Google Maps API

-The first thing to do is receiving an API key associated to your site, from this page http://code.google.com/intl/it-IT/apis/maps/signup.html

-In our file we must include the api script in the header section:
<script src=
"http://maps.google.com/maps?file=api&amp;v=2&amp;key=<i>yourkeyhere</i>&amp;sensor=false"
type="text/javascript">
</script>
-In the body section, we must place a div tag containing the area where we are going to visualize our map:
<div id="map_canvas" style=
"width: 500px; height: 400px; border-width: 1px;" align="right">
</div>
Obviously we'll change the style content at our needs.
-Now we can write the script which will set our custom map:
1.
The first and most important function we need to write is called initialize()
<script type="text/javascript">
//<![CDATA[
var home;
var map; 
var directions;
var marker;

function initialize() 
{
var map = document.getElementById('map_canvas');

home = new GLatLng(x,y); //here we set the centre coordinates

map = new GMap2(map);                  
map.setCenter(home, 15); //15 is the zoom scale
map.setUIToDefault(); //using the GMaps aspect
map.setMapType(G_SATELLITE_MAP);//visualize the satellite image
}
//]]>
</script>
Note how is structured the code: variable initialization, get the div area, and set the basic options.
Now we have our map, and we can pan and zoom it as on the google maps site.

2.the first extension is the Ad Manager which visualize the Adsense on the map
var publisher_id = "your-publisher-id-here";
var adsManagerOptions = {
maxAdsOnMap : 2, //how many ads displayed
style: 'adunit', //the type
};
adsManager = new GAdsManager(map, publisher_id, adsManagerOptions);
adsManager.enable();

3.placing a marker
function createMarker(map, point, stringa)
{
var marker = new GMarker(point);         
GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml(stringa);});
map.addOverlay(marker);
return marker;
} 
The function requires: the map object, the coordinates where it will be placed, and the html text to be displayed.

4.creating a route using markers:
function createRoute(map, marker1, marker2)
{
directions = new GDirections(map);
var from=marker1.getPoint();
var to=marker2.getPoint();
var pointsArray=[from,to];
GEvent.addListener(directions,"load", function onGDirectionsLoad() { 
var polyline = directions.getPolyline(); 
polyline.color="#FF0000"; 
map.addOverlay(polyline); 
} ); 
directions.loadFromWaypoints(pointsArray);
}
You can extend it to more markers adding the point to pointsArray.
The function requires: map object and the markers from which extract the coordinates.
If you don't want to use markers, you can specify an array of Points. In the function you can set the vars from and to with GPoints.

Nessun commento:

Posta un commento

Lascia un commento...