Monday, March 8, 2010

Mixing Google Maps with Raphael JS (I)

Raphael JS is a JavaScript library built to simplify working with vector graphics (for the web) .
This library is useful in Google Maps when you want to do something that simple html is not enough.

What to do:

1) First, create a webpage:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
  <title></title>
</head>

<body>

</body>

</html>

2) Load the scripts in the head of the page:

<script src="raphael-min.js" type="text/javascript" charset="utf-8"></script>
    <script src="http://maps.google.com/maps?file=api&amp;v=2&key=ABQIAAAAnQbookkle8hxu22fQ6NbQhQNPFMnb_xkSQN8CfaH-8v21m5ByRQZ6mgEZeD_g20a0Wrd6MNogUCNZQ" type="text/javascript"></script>

3) Add page elements inside the body tag:

<div id="map_canvas" style="width: 500px; height: 300px"></div>

4) Create the script that do the rest of the  work in the head:

<script type="text/javascript" charset="utf-8">
            function initialize() {
      if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("map_canvas"));
        map.setCenter(new GLatLng(44, 11), 1);
        var details=document.createElement('div');
        details.innerHTML="<div id='r_canvas' style=' -moz-user-select: none; position: absolute; right: 0px; bottom: 0px;' class='gmnoprint'></div>"
        document.getElementById('map_canvas').appendChild(details);

        raph();
      }
    }
            function raph() {

                var r = Raphael("r_canvas", 100, 100);
                var sq = 1;


                    var color = Raphael.getColor();
                    (function (a, c) {

                    r.rect(0,0, 100,100).attr({"stroke-width":0,fill: "#000", opacity: 0.5}).mouseover(changerad)})(sq, "black");
                    r.text(50,50,"mouse over me").attr({"fill":"yellow","font-size":12});



                          }
                Raphael.getColor.reset();


function changerad() {



 this.animate({cx: 50, r: 40}, 1000, "bounce");


 }



    </script>

5) After doing all above and changing the API key you are ready to test it on your server. It should look like this:

1 comment:

  1. Hi! i find this useful...

    i have a question... i cover all the map with raphael and use the map like a background but i have to resend to the map mouse event. I capture the event and i use them for raphael but i want also to resend to do like the move of the map... thanks
    Ale

    ReplyDelete