GMLib, la librairie de composants qui facilite la vie des programmeurs Delphi

L'intégration de google maps dans une application Delphi passe par :
- l'ajout de code javascript interprétables par google maps;
- l'utilisation de composants SIG dédiés qui encapsulent les fonctionnalités de l'API google maps.

Voici deux exemples, l'un utilisant du code javascript à l'intérieur de Delphi et l'autre utilisant les méthodes fournies par un composant SIG.

1. Utilisation de javascript
On commence par définir la constante texte qui renseigne le navigateur afin d'exécuter le code javascript et rend le résultats sous forme de carte. Puis, dans la méthode OnCreate de la forme on appelle la fonction de chargement.

uses
   ActiveX;

{$R *.dfm}

const
HTMLStr: String = //i put The code for the web page page wich load the google maps in a string const, you can use an external html file too or embed the page in a resource and then load in a stream
'<html> '+
'<head> '+
'<meta name="viewport" content="initial-scale=1.0, user-scalable=yes" /> '+
'<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script> '+
'<script type="text/javascript"> '+
''+
''+//Declare the globals vars to be used in the javascript functions
'  var geocoder; '+
'  var map;  '+
'  var trafficLayer;'+
'  var bikeLayer;'+
''+
''+
'  function initialize() { '+
'    geocoder = new google.maps.Geocoder();'+
'    var latlng = new google.maps.LatLng(40.714776,-74.019213); '+ //Set the initial coordinates for the map
'    var myOptions = { '+
'      zoom: 13, '+
'      center: latlng, '+
'      mapTypeId: google.maps.MapTypeId.ROADMAP '+ //Set the default type map
'    }; '+
'    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); '+
'    trafficLayer = new google.maps.TrafficLayer();'+ //Create the traffic Layer instance
'    bikeLayer = new google.maps.BicyclingLayer();'+ //Create the Bicycling Layer instance
'  } '+
''+
''+
'  function codeAddress(address) { '+ //function to translate an address to coordinates and put and marker.
'    if (geocoder) {'+
'      geocoder.geocode( { address: address}, function(results, status) { '+
'        if (status == google.maps.GeocoderStatus.OK) {'+
'          map.setCenter(results[0].geometry.location);'+
'          var marker = new google.maps.Marker({'+
'              map: map,'+
'              position: results[0].geometry.location'+
'          });'+
'        } else {'+
'          alert("Geocode was not successful for the following reason: " + status);'+
'        }'+
'      });'+
'    }'+
'  }'+
''+
''+
'  function GotoLatLng(Lat, Lang) { '+ //Set the map in the coordinates and put a marker
'   var latlng = new google.maps.LatLng(Lat,Lang);'+
'   map.setCenter(latlng);'+
'   var marker = new google.maps.Marker({'+
'      position: latlng, '+
'      map: map,'+
'      title:Lat+","+Lang'+
'  });'+
'  }'+
''+
''+
'  function TrafficOn()   { trafficLayer.setMap(map); }'+ //Activate the Traffic layer
''+
'  function TrafficOff()  { trafficLayer.setMap(null); }'+
''+''+
'  function BicyclingOn() { bikeLayer.setMap(map); }'+//Activate the Bicycling layer
''+
'  function BicyclingOff(){ bikeLayer.setMap(null);}'+
''+
'  function StreetViewOn() { map.set("streetViewControl", true); }'+//Activate the streeview control
''+
'  function StreetViewOff() { map.set("streetViewControl", false); }'+
''+
''+'</script> '+
'</head> '+
'<body onload="initialize()"> '+
'  <div id="map_canvas" style="width:100%; height:100%"></div> '+
'</body> '+
'</html> ';

procedure TfrmMain.FormCreate(Sender: TObject);
var
  aStream     : TMemoryStream;
begin
   WebBrowser1.Navigate('about:blank'); //Set the location to an empty page
    if Assigned(WebBrowser1.Document) then
    begin
      aStream := TMemoryStream.Create; //create a TStem to load the Page from the string
      try
         aStream.WriteBuffer(Pointer(HTMLStr)^, Length(HTMLStr)); //Copy the string to the stream
         //aStream.Write(HTMLStr[1], Length(HTMLStr));
         aStream.Seek(0, soFromBeginning);
         (WebBrowser1.Document as IPersistStreamInit).Load(TStreamAdapter.Create(aStream));//Load the page from the stream
      finally
         aStream.Free;
      end;
      HTMLWindow2 := (WebBrowser1.Document as IHTMLDocument2).parentWindow; //Set the instance of the parentWindow to call the javascripts functions
    end;
end;

Bien évidemment ce code n'est pas destiné aux débutants et il n'est donné qu'à titre d'exemple, il a était copier de cet endroit, voua allez vite remarquer qu'il faut avoir un minimum de connaissance en javascript, ce qui n'est pas toujours le cas pour un programmeur Delphi, et des connaissances assez solide en API google maps version 3 pour un résultats pas vraiment très encourageant, simple avis.

2. Utilisation de composants SIG
Ma tournée sur la toile m'a guidé vers l'excellente bibliothèque SIG GMLib, elle encapsule une grande partie de l'API google maps. Donc pour son utilisation rien de plus simple, examinez ce bout de code.

procedure TfmMain.GMMap1AfterPageLoaded(Sender: TObject; First: Boolean);
begin
  if First then
  try
    GMMap1.DoMap;
  Except
    ShowMessage('Erreur connxion internet...');
  end;
end;

Rien de compliquer même un débutant le lira facilement. On commence par déposer un composant GMMap sur non forme puis dans l'événement OnAfterPageLoaded on "dessine" notre carte par le biais de la méthode DoMap.

A vous de voir maintenant, laquelle des deux méthodes est facile à utiliser ? 







Commentaires

Posts les plus consultés de ce blog

Cours 1er - LE PROJET D'UN SIG - Partie II

Cours 1er - LES SOLUTIONS SIG - Parti III

Cours 1er - INTRODUCTION GENERALE AUX SIGs - Partie I