Aller au contenu. | Aller à la navigation

Université
Facultés
Études et Formations
Recherche
Service à la société
International

Manuel API

Procédure d'intégration de cartes dynamiques au sein d'une page web

 

Qu'est-ce que l'API Google ?

Google propose plusieurs API. Une interface de programmation (Application Programming Interface ou API) est une interface fournie par un programme informatique. Elle permet l'interaction des programmes les uns avec les autres, de manière analogue à une interface homme-machine, qui rend possible l'interaction entre un homme et une machine.

Concrètement, il est possible d'insérer une petite fenêtre Google Map ou Google Earth dans une page web.

 

Le code HTML des cartes Google Maps

Allez sur http://maps.google.fr/ et cherchez l'endroit pour lequel vous souhaitez une carte (ex. : tapez Londres dans la barre de recherche). Ensuite cliquez sur "lien" dans le coin supérieur droit. Deux codes vous sont proposés :

  • une URL : http://maps.google.fr/maps?f=q&source=s_q&hl=fr&geocode=&q=londres&aq=&sll=46.75984,1.738281&sspn=10.991448,19.753418&ie=UTF8&hq=&hnear=Cit%C3%A9+de+Westminster,+Londres,+Royaume-Uni&t=h&z=10
  • un code HTML : <iframe width="425" height="350" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://maps.google.fr/maps?f=q&amp;source=s_q&amp;hl=fr&amp;geocode=&amp;q=londres&amp;aq=&amp;sll=46.75984,1.738281&amp;sspn=10.991448,19.753418&amp;ie=UTF8&amp;hq=&amp;hnear=Cit%C3%A9+de+Westminster,+Londres,+Royaume-Uni&amp;t=h&amp;z=10&amp;ll=51.500152,-0.126236&amp;output=embed"></iframe><br /><small><a href="http://maps.google.fr/maps?f=q&amp;source=embed&amp;hl=fr&amp;geocode=&amp;q=londres&amp;aq=&amp;sll=46.75984,1.738281&amp;sspn=10.991448,19.753418&amp;ie=UTF8&amp;hq=&amp;hnear=Cit%C3%A9+de+Westminster,+Londres,+Royaume-Uni&amp;t=h&amp;z=10&amp;ll=51.500152,-0.126236" style="color:#0000FF;text-align:left">Agrandir le plan</a></small>

Insertion d'une carte dans une page "classique"

C'est ce deuxième code qu'il faut utiliser pour intégrer la carte dans votre page. Dans une page HTML classique, à l'endroit où l'on veut afficher la carte, insérer le code. Par exemple :

<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Document sans nom</title>
</head>

<body>
<p>Voici un exemple d'intégration du carte Google Maps de Londres</p>
<p>&nbsp; </p>

<iframe width="425" height="350" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://maps.google.fr/maps?f=q&amp;source=s_q&amp;hl=fr&amp;geocode=&amp;q=londres&amp;aq=&amp;sll=46.75984,1.738281&amp;sspn=10.991448,19.753418&amp;ie=UTF8&amp;hq=&amp;hnear=Cit%C3%A9+de+Westminster,+Londres,+Royaume-Uni&amp;t=h&amp;z=10&amp;ll=51.500152,-0.126236&amp;output=embed"></iframe><br /><small><a href="http://maps.google.fr/maps?f=q&amp;source=embed&amp;hl=fr&amp;geocode=&amp;q=londres&amp;aq=&amp;sll=46.75984,1.738281&amp;sspn=10.991448,19.753418&amp;ie=UTF8&amp;hq=&amp;hnear=Cit%C3%A9+de+Westminster,+Londres,+Royaume-Uni&amp;t=h&amp;z=10&amp;ll=51.500152,-0.126236" style="color:#0000FF;text-align:left">Agrandir le plan</a></small>

</body>
</html>

Ce qui donnera une page web de ce style.

 

Insertion d'une carte dans une page gérée par CMS

Pour les pages créées avec un CMS (Content Management System, type Plone, Google Sites ou Joomla!), il y a recodage lors d'intégration d'un code HTML contenant certaines balises. Le code donné par Google Maps contient une balise <iframe>. Le présent site est créé avec le CMS Plone qui est compatible avec iframe.

Personnalisation des cartes (code HTML)

Il est possible, bien sûr, de modifier les codes pour voir affichés des outils supplémentaires (ex. barre de recherche). Voir la documentation ici. On utilisera de préférence les API v3.0.

Si l'on utilise un code complexe dans un CMS beaucoup de balises, scripts, etc. seront supprimées lors de la compilation. Une solution est de créer une page HTML, hébergée sur un FTP ou Dropbox et d'appeler cette page dans un encart.

Par exemple, on créé la page HTML suivante pour afficher une Google Maps en version 3.0 :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Google Maps V3 API Sample</title>
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
    <script type="text/javascript">

      function initialize() {
        var mapDiv = document.getElementById('map-canvas');
        var map = new google.maps.Map(mapDiv, {
          center: new google.maps.LatLng(37.4569, -122.1569),
          zoom: 13,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        });
     
        google.maps.event.addListenerOnce(map, 'tilesloaded', function() {
          window.setTimeout(function() {
            map.panTo(new google.maps.LatLng(37.4569, -122.1569));
          }, 1000);
        });
      }
 

      google.maps.event.addDomListener(window, 'load', initialize);
    </script>
  </head>
  <body style="font-family: Arial; border: 0 none;">
    <div id="map-canvas" style="width: 500px; height: 400px"></div>
  </body>
</html>

Dans ce code, les lignes à personnaliser sont :
  • center: new google.maps.LatLng(37.4569, -122.1569) : Latitude et Longitude de centrage de la carte
  • mapTypeId: google.maps.MapTypeId.ROADMAP : type de carte que l'on veut afficher (il y en a 4 : ROADMAP, SATELLITE, HYBRID, TERRAIN))
  • map.panTo(new google.maps.LatLng(37.4569, -122.1569)) : même Lat et Long que précédemment
  • <div id="map-canvas" style="width: 500px; height: 400px"></div> : largeur et hauteur de la carte (en pixels)

Cette page est stockée sur Dropbox à l'adresse suivante http://dl.dropbox.com/u/20627986/search2.html :

<iframe id="map" type="text/html" data="http://dl.dropbox.com/u/20627986/search2.html" style="width:640px;height:480px;">

</iframe><!--[if lte IE 7]><script type="text/javascript">(function(){var o=document.getElementById('map');var i=document.createElement('iframe');i.setAttribute('src',o.getAttribute('data'));i.style.width=o.style.width;i.style.height=o.style.height;o.parentNode.replaceChild(i,o);})();</script><![endif]-->


Ce qui donne :

 

Insertion d'une carte avec barre de recherche

Pour insérer une carte avec une barre de recherche de lieux, on utilisera le code suivant :

 

!--
 Copyright 2008 Google Inc.
 Licensed under the Apache License, Version 2.0:
 http://www.apache.org/licenses/LICENSE-2.0
 -->
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Google AJAX Local Search API + Maps API v3 demo</title>
    <link href="http://www.google.com/uds/css/gsearch.css" rel="stylesheet" type="text/css"/>
    <link href="./places.css" rel="stylesheet" type="text/css"/>

    <script src="http://maps.google.com/maps/api/js?sensor=false"></script>

    <script src="http://www.google.com/uds/api?file=uds.js&amp;v=1.0&amp;key=ABQIAAAAjU0EJWnWPMv7oQ-jjS7dYxQ82LsCgTSsdpNEnBsExtoeJv4cdBSUkiLH6ntmAr_5O4EfjDwOa0oZBQ" type="text/javascript"></script>
    <script type="text/javascript">
    //<![CDATA[

    // Our global state
    var gLocalSearch;
    var gMap;
    var gInfoWindow;
    var gSelectedResults = [];
    var gCurrentResults = [];
    var gSearchForm;

    // Create our "tiny" marker icon
    var gYellowIcon = new google.maps.MarkerImage(
      "http://labs.google.com/ridefinder/images/mm_20_yellow.png",
      new google.maps.Size(12, 20),
      new google.maps.Point(0, 0),
      new google.maps.Point(6, 20));
    var gRedIcon = new google.maps.MarkerImage(
      "http://labs.google.com/ridefinder/images/mm_20_red.png",
      new google.maps.Size(12, 20),
      new google.maps.Point(0, 0),
      new google.maps.Point(6, 20));
    var gSmallShadow = new google.maps.MarkerImage(
      "http://labs.google.com/ridefinder/images/mm_20_shadow.png",
      new google.maps.Size(22, 20),
      new google.maps.Point(0, 0),
      new google.maps.Point(6, 20));

     // Set up the map and the local searcher.
    function OnLoad() {

      // Initialize the map with default UI.
      gMap = new google.maps.Map(document.getElementById("map"), {
        center: new google.maps.LatLng(0, 0),
        zoom: 1,
        mapTypeId: 'satellite'
      });
      // Create one InfoWindow to open when a marker is clicked.
      gInfoWindow = new google.maps.InfoWindow;
      google.maps.event.addListener(gInfoWindow, 'closeclick', function() {
        unselectMarkers();
      });

      // Initialize the local searcher
      gLocalSearch = new GlocalSearch();
      gLocalSearch.setSearchCompleteCallback(null, OnLocalSearch);
    }

    function unselectMarkers() {
      for (var i = 0; i < gCurrentResults.length; i++) {
        gCurrentResults[i].unselect();
      }
    }

    function doSearch() {
      var query = document.getElementById("queryInput").value;
      gLocalSearch.setCenterPoint(gMap.getCenter());
      gLocalSearch.execute(query);
    }

    // Called when Local Search results are returned, we clear the old
    // results and load the new ones.
    function OnLocalSearch() {
      if (!gLocalSearch.results) return;
      var searchWell = document.getElementById("searchwell");

      // Clear the map and the old search well
      searchWell.innerHTML = "";
      for (var i = 0; i < gCurrentResults.length; i++) {
        gCurrentResults[i].marker().setMap(null);
      }
      // Close the infowindow
      gInfoWindow.close();

      gCurrentResults = [];
      for (var i = 0; i < gLocalSearch.results.length; i++) {
        gCurrentResults.push(new LocalResult(gLocalSearch.results[i]));
      }

      var attribution = gLocalSearch.getAttribution();
      if (attribution) {
        document.getElementById("searchwell").appendChild(attribution);
      }

      // Move the map to the first result
      var first = gLocalSearch.results[0];
      gMap.setCenter(new google.maps.LatLng(parseFloat(first.lat),
                                            parseFloat(first.lng)));

    }

    // Cancel the form submission, executing an AJAX Search API search.
    function CaptureForm(searchForm) {
      gLocalSearch.execute(searchForm.input.value);
      return false;
    }



    // A class representing a single Local Search result returned by the
    // Google AJAX Search API.
    function LocalResult(result) {
      var me = this;
      me.result_ = result;
      me.resultNode_ = me.node();
      me.marker_ = me.marker();
      google.maps.event.addDomListener(me.resultNode_, 'mouseover', function() {
        // Highlight the marker and result icon when the result is
        // mouseovered.  Do not remove any other highlighting at this time.
        me.highlight(true);
      });
      google.maps.event.addDomListener(me.resultNode_, 'mouseout', function() {
        // Remove highlighting unless this marker is selected (the info
        // window is open).
        if (!me.selected_) me.highlight(false);
      });
      google.maps.event.addDomListener(me.resultNode_, 'click', function() {
        me.select();
      });
      document.getElementById("searchwell").appendChild(me.resultNode_);
    }

    LocalResult.prototype.node = function() {
      if (this.resultNode_) return this.resultNode_;
      return this.html();
    };

    // Returns the GMap marker for this result, creating it with the given
    // icon if it has not already been created.
    LocalResult.prototype.marker = function() {
      var me = this;
      if (me.marker_) return me.marker_;
      var marker = me.marker_ = new google.maps.Marker({
        position: new google.maps.LatLng(parseFloat(me.result_.lat),
                                         parseFloat(me.result_.lng)),
        icon: gYellowIcon, shadow: gSmallShadow, map: gMap});
      google.maps.event.addListener(marker, "click", function() {
        me.select();
      });
      return marker;
    };

    // Unselect any selected markers and then highlight this result and
    // display the info window on it.
    LocalResult.prototype.select = function() {
      unselectMarkers();
      this.selected_ = true;
      this.highlight(true);
      gInfoWindow.setContent(this.html(true));
      gInfoWindow.open(gMap, this.marker());
    };

    LocalResult.prototype.isSelected = function() {
      return this.selected_;
    };

    // Remove any highlighting on this result.
    LocalResult.prototype.unselect = function() {
      this.selected_ = false;
      this.highlight(false);
    };

    // Returns the HTML we display for a result before it has been "saved"
    LocalResult.prototype.html = function() {
      var me = this;
      var container = document.createElement("div");
      container.className = "unselected";
      container.appendChild(me.result_.html.cloneNode(true));
      return container;
    }

    LocalResult.prototype.highlight = function(highlight) {
      this.marker().setOptions({icon: highlight ? gRedIcon : gYellowIcon});
      this.node().className = "unselected" + (highlight ? " red" : "");
    }

    GSearch.setOnLoadCallback(OnLoad);
    //]]>
    </script>
  </head>
  <body style="font-family: Arial, sans-serif; font-size: small;">
    <div style="width: 500px;">
      <div style="margin-bottom: 5px;">

        <div>
          <input type="text" id="queryInput" value="entrez un lieu" style="width: 250px;"/>
          <input type="button" value="Chercher" onclick="doSearch()"/>
        </div>
      </div>
      <div style="position: absolute; left: 540px;">
        <div id="searchwell"></div>
      </div>
      <div id="map" style="height: 350px; border: 1px solid #979797;"></div>

    </div>

  </body>
</html>

 

N.B. : La bonne exécution de ce code nécessite une clé API (en gras dans le code), clé unique liée à la page sur laquelle sera insérée la carte. Cette clé doit donc être modifiée si l'on souhaite utiliser le code sur un autre site. Une clé API peut être obtenue ici.

Voici le résultat :


Agrandir le plan" type="text/html">