Google Maps et OpenStreetMap

Partagez votre expérience de PureBasic avec les autres utilisateurs.
Avatar de l’utilisateur
MetalOS
Messages : 1510
Inscription : mar. 20/juin/2006 22:17
Localisation : Lorraine
Contact :

Google Maps et OpenStreetMap

Message par MetalOS »

J'ouvre un poste sur tous ce qui concerne des codes sur Google Maps et OpenStreetMap. Ce qui pourrai aider du monde qui cherche des exemple sur le sujet.

Je commence avec un code sur Google Maps. C'est un vieux code que j'avais fait en me basant sur une procédure que j'avais trouvé sur le forum anglais.

Code : Tout sélectionner

; Google Maps V1
; By MetalOS

Enumeration 
   #ROADMAP 
   #SATELLITE 
   #TERRAIN 
   #HYBRID 
EndEnumeration 

;{ Windows 
Enumeration 
  #Window_0 
EndEnumeration 
;} 
;{ Gadgets 
Enumeration 
  #Image_0 
  #Button_1 
  #Button_2 
  #Button_3 
  #Button_4 
  #String_5 
  #Button_6 
  #String_7 
  #ComboBox_8 
  #TrackBar_9 
  #Button_10 
EndEnumeration 
;} 
;{ Images 
Enumeration 
  #Image_Image_0 
EndEnumeration 
;} 
Define.l Event, EventWindow, EventGadget, EventType, EventMenu 
;} 
InitNetwork() 
UsePNGImageDecoder() 

Global MapType, myImage,GX$,GY$,p 

Procedure.l getMapImage( MapAddress.s, Zoom=10, MapType = #ROADMAP, Markers.s = "" ) 
   RetVal = 0 
   If Markers <> "" 
      myRequestTwo.s = "/maps/api/staticmap?center="+ URLEncoder(MapAddress) + "&" + URLEncoder(Markers) + "&zoom=" + Str(Zoom) + "&size=500x500" 
   Else 
      myRequestTwo.s = "/maps/api/staticmap?center="+ URLEncoder(MapAddress) + "&zoom=" + Str(Zoom) + "&size=500x500" 
   EndIf 
   Select MapType 
      Case #SATELLITE 
         myRequestTwo.s + "&maptype=satellite"  
      Case #TERRAIN 
         myRequestTwo.s + "&maptype=terrain" 
      Case #HYBRID 
         myRequestTwo.s + "&maptype=hybrid" 
      Default 
         myRequestTwo.s + "&maptype=roadmap"  
   EndSelect 
    
   myRequestTwo.s + "&sensor=false" 
    
   myConnection = OpenNetworkConnection("maps.google.com", 80, #PB_Network_TCP) 
   If myConnection = 0 
      ProcedureReturn 0 
   EndIf 
   myRequest.s = "GET "+ myRequestTwo + " HTTP/1.0" + #CRLF$ 
   myRequest.s + "Content-Type: application/x-www-form-urlencoded; charset=iso-8859-1" + #CRLF$ 
   myRequest.s + "Host: maps.google.com" + #CRLF$ + #CRLF$ 
   *buffer = AllocateMemory(65535) 
   *bufferTwo = AllocateMemory(65535) 
   bfTwoPtr = 0 
   mSize = 65535 
   SendNetworkString(myConnection, myRequest) 
   dwBytes = 1 
   While dwBytes > 0 
      dwBytes = ReceiveNetworkData(myConnection, *buffer, 65535) 
      If dwBytes > 0 
         If (*bufferTwo + dwBytes) >= mSize 
            mSize + 65535 
            *bufferTwo = ReAllocateMemory(*bufferTwo, mSize) 
         EndIf 
         CopyMemory(*buffer, (*bufferTwo+bfTwoPtr), dwBytes) 
         bfTwoPtr + dwBytes 
      EndIf 
   Wend 
   CloseNetworkConnection(myConnection) 
   FreeMemory(*buffer) 
   dblCrlf.s = #CRLF$+#CRLF$ 
   found = 0 
   For k = 0 To bfTwoPtr 
      If k > bfTwoPtr 
         Break 
      EndIf 
      If PeekS(*bufferTwo+k, 4) = dblCrlf 
         found = k 
         headerInfo.s = PeekS(*bufferTwo, k) 
         dataBeginSpot = (k + 4) 
         *dataBegin = (*bufferTwo + dataBeginSpot) 
         dataLength    = (bfTwoPtr - dataBeginSpot) 
         Break 
      EndIf 
   Next 
   RetVal = CatchImage(#PB_Any, *dataBegin, dataLength) 
   FreeMemory(*bufferTwo) 
   ProcedureReturn RetVal 
EndProcedure 

Procedure OpenWindow_Window_0() 
  If OpenWindow(#Window_0, 477, 84, 760, 509, "Google Maps V1 by MetalOS", #PB_Window_SystemMenu|#PB_Window_SizeGadget|#PB_Window_MinimizeGadget|#PB_Window_TitleBar) 
      ImageGadget(#Image_0, 5, 5, 500, 500, 0, #PB_Image_Border) 
      ButtonGadget(#Button_1, 600, 285, 40, 60, "H") 
      ButtonGadget(#Button_2, 645, 345, 40, 60, "D") 
      ButtonGadget(#Button_3, 555, 345, 40, 60, "G") 
      ButtonGadget(#Button_4, 600, 405, 40, 60, "B") 
      StringGadget(#String_5, 535, 55, 60, 20, "48.265") 
      ButtonGadget(#Button_6, 600, 345, 40, 60, "Ok") 
      StringGadget(#String_7, 535, 95, 60, 20, "6.358") 
      ComboBoxGadget(#ComboBox_8, 520, 150, 225, 20) 
      TrackBarGadget(#TrackBar_9, 515, 470, 230, 30, 1, 20, #PB_TrackBar_Ticks):SetGadgetState(#TrackBar_9,10) 
      ButtonGadget(#Button_10, 625, 50, 110, 65, "Capturer") 
     AddGadgetItem(#ComboBox_8, -1,"ROADMAP") 
     AddGadgetItem(#ComboBox_8, -1,"SATELLITE") 
     AddGadgetItem(#ComboBox_8, -1,"TERRAIN") 
     AddGadgetItem(#ComboBox_8, -1,"HYBRID") 
     SetGadgetState(#ComboBox_8,0) 
  EndIf 
EndProcedure 

Procedure GetNewMap() 
        GX$=GetGadgetText(#String_5) 
        GY$=GetGadgetText(#String_7) 
        myImage = getMapImage(GX$+","+GY$,GetGadgetState(#TrackBar_9),GetGadgetState(#ComboBox_8)) 
        If myImage 
          SetGadgetState(#Image_0,ImageID(myImage)) 
        EndIf 
EndProcedure 



OpenWindow_Window_0() 

;{- Event loop 
Repeat 
  Event = WaitWindowEvent() 
  Select Event 
    ; /////////////////// 
    Case #PB_Event_Gadget 
      EventGadget = EventGadget() 
      EventType = EventType() 
      If EventGadget = #Image_0 
      ElseIf EventGadget = #Button_1 
        Up.f=ValF(GetGadgetText(#String_5))+0.005 
        SetGadgetText(#String_5,StrF(Up)) 
        GetNewMap() 
      ElseIf EventGadget = #Button_2 
        Up.f=ValF(GetGadgetText(#String_7))+0.005 
        SetGadgetText(#String_7,StrF(Up)) 
        GetNewMap() 
      ElseIf EventGadget = #Button_3 
        Up.f=ValF(GetGadgetText(#String_7))-0.005 
        SetGadgetText(#String_7,StrF(Up)) 
        GetNewMap() 
      ElseIf EventGadget = #Button_4 
        Up.f=ValF(GetGadgetText(#String_5))-0.005 
        SetGadgetText(#String_5,StrF(Up)) 
        GetNewMap() 
      ElseIf EventGadget = #Button_10 
        If myImage 
            SaveImage(myImage,Str(p)+"_"+GX$+"_"+GY$+".bmp") 
          p+1 
        EndIf 
      
      ElseIf EventGadget = #Button_6 
              GetNewMap() 
            ElseIf EventGadget = #ComboBox_8 
              If MapType<>GetGadgetState(#ComboBox_8) 
                 MapType=GetGadgetState(#ComboBox_8) 
                GetNewMap()    
              EndIf 
              
      ElseIf EventGadget = #TrackBar_9 
       GetNewMap() 
      EndIf 
    ; //////////////////////// 
    Case #PB_Event_CloseWindow 
      EventWindow = EventWindow() 
      If EventWindow = #Window_0 
        CloseWindow(#Window_0) 
        Break 
      EndIf 
  EndSelect 
ForEver 
; 
;} 
Avatar de l’utilisateur
MetalOS
Messages : 1510
Inscription : mar. 20/juin/2006 22:17
Localisation : Lorraine
Contact :

Re: Google Maps et OpenStreetMap

Message par MetalOS »

Voici un exemple avec Google Earth trouvé sur un forum Russe de Purebasic. (Dans le code et marqué Kernadec, c'est peut être de lui au départ ce code).

Enregistrer ce code sous le nom "Maps.pb"

Code : Tout sélectionner

;   http://www.purebasic.fr/english/viewtopic.php?f=13&t=35188&hilit=JavaScript
;
;
;

#DISPATCH_METHOD = $1
#DISPATCH_PROPERTYGET = $2
#DISPATCH_PROPERTYPUT = $4
#DISPATCH_PROPERTYPUTREF = $8

DataSection
   IID_IHTMLDocument: ; {626FC520-A41E-11CF-A731-00A0C9082637}
      Data.l $626FC520
      Data.w $A41E, $11CF
      Data.b $A7, $31, $00, $A0, $C9, $08, $26, $37
      
   IID_NULL: ; {00000000-0000-0000-0000-000000000000}
      Data.l $00000000
      Data.w $0000, $0000
      Data.b $00, $00, $00, $00, $00, $00, $00, $00       
EndDataSection

Procedure MakeBSTR(String$)
  Unicode$ = Space(Len(String$)*2+2)
   MultiByteToWideChar_(#CP_ACP, 0, @String$, -1, @Unicode$, Len(String$)*2+2)
  ProcedureReturn SysAllocString_(@Unicode$)
EndProcedure

Procedure.s ReadBSTR(bstr)
   length = WideCharToMultiByte_(#CP_ACP, 0, bstr, -1, 0, 0, 0, 0)
   Text$ = Space(length)
   WideCharToMultiByte_(#CP_ACP, 0, bstr, -1, @Text$, length, 0, 0)   
 ProcedureReturn Text$
EndProcedure

Procedure.s StringFromVARIANT(*var.VARIANT)
   If VariantChangeType_(*var, *var, $2, #VT_BSTR) = #S_OK
      Result$ = ReadBSTR(*var\bstrVal)
      SysFreeString_(*var\bstrVal)
   Else
      Result$ = "Îøèáêà : Íå óäàëîñü ïðåîáðàçîâàòü â VARIANT Ñòðîêà !"
   EndIf
 ProcedureReturn Result$
EndProcedure

Procedure.s ExecuteJavaScript(Gadget, Function$, Arguments$, Separator$)
   Result$ = "Îøèáêà"

   Browser.IWebBrowser2 = GetWindowLong_(GadgetID(Gadget), #GWL_USERDATA)
   If Browser\get_Document(@DocumentDispatch.IDispatch) = #S_OK
      If DocumentDispatch\QueryInterface(?IID_IHTMLDocument, @Document.IHTMLDocument) = #S_OK
         If Document\get_Script(@Script.IDispatch) = #S_OK
            
            bstr_command = MakeBSTR(Function$)
            result = Script\GetIDsOfNames(?IID_NULL, @bstr_command, 1, 0, @dispID.l)
            If result = #S_OK
               ; ïðîàíàëèçèðîâàòü àðãóìåíòû          
               If Trim(Arguments$) = ""
                  Count = 0
                  *Arguments = 0
               Else           
                  Count = CountString(Arguments$, Separator$)+1
                  *Arguments = AllocateMemory(SizeOf(VARIANT)*Count)       
                  *Arg.VARIANT = *Arguments
                  
                  For i = 1 To Count           
                     *Arg\vt = #VT_BSTR
                     *Arg\bstrVal = MakeBSTR(StringField(Arguments$, i, Separator$))
                     *Arg + SizeOf(VARIANT)
                  Next i
               EndIf
               
               params.DISPPARAMS\cArgs = Count
               params\cNamedArgs = 0
               params\rgvarg = *Arguments
               
               result = Script\Invoke(dispID, ?IID_NULL, 0, #DISPATCH_METHOD, @params, @varResult.VARIANT, 0, 0)

               If result = #S_OK
                  Result$ = StringFromVARIANT(@varResult)
               Else
                  Message$ = Space(3000)
                  FormatMessage_(#FORMAT_MESSAGE_IGNORE_INSERTS|#FORMAT_MESSAGE_FROM_SYSTEM, 0, result, 0, @Message$, 3000, 0)         
                  Result$ = "Îøèáêà: Invoke() "+Message$           
               EndIf
               
               If *Arguments
                  *Arg.VARIANT = *Arguments
                  For i = 1 To Count
                     SysFreeString_(*Arg\bstrVal)
                     *Arg + SizeOf(VARIANT) 
                  Next i         
                  FreeMemory(*Arguments)
               EndIf
               
            Else
               Message$ = Space(3000)
               FormatMessage_(#FORMAT_MESSAGE_IGNORE_INSERTS|#FORMAT_MESSAGE_FROM_SYSTEM, 0, result, 0, @Message$, 3000, 0)         
               Result$ = "Îøèáêà: GetIDsOfNames() "+Message$           
            EndIf
            SysFreeString_(bstr_command)
                                 
            Script\Release()
         EndIf
         Document\Release()
      EndIf
      DocumentDispatch\Release()
   EndIf

   ProcedureReturn Result$
EndProcedure

#web_1 = 1

strfile$ = "file:///" + GetCurrentDirectory() + "google.html"

If OpenWindow(0,0,0,812,700,"Google Earth",#PB_Window_SizeGadget | #PB_Window_SystemMenu | #PB_Window_MinimizeGadget |#PB_Window_MaximizeGadget | #PB_Window_ScreenCentered)
         WebGadget(#Web_1, -10, -10, 850, 660, strfile$) ;,#PB_Web_Mozilla )
         ButtonGadget(2,20, 670,60,20,"Ìåòêè ")
         ButtonGadget(3,90, 670,60,20,"ZigZag")
         ButtonGadget(4,160,670,100,20,"Ïåðåéòè ïî ìåòêå")
       
 Repeat 
  Event = WaitWindowEvent()  
  If Event = #PB_Event_Gadget     
    Select EventGadget()    
      Case 2 
        Executejavascript(#web_1,"CreatePlaceMark","Purebasic","")
      Case 3 
        Executejavascript(#web_1,"CreateZigZag","","") 
      Case 4   
        Executejavascript(#web_1,"LookAt","300,0;174,8128;-36,8255",";")       
        ;Executejavascript(#web_1,"LookAt","300,0; 31,9549; 46,9986",";") ; ìîé äîì
        ;Executejavascript(#web_1,"LookAt","300,0;-0,363;49,1872",";") ; kernadec æèâåò â ãîðîäå Êàíà ãîðîäà Èëè çàìîê Âèëüãåëüìà Çàâîåâàòåëÿ â Íîðìàíäèè ãåðöîã ïðåäêà êîðîëåâà Àíãëèè (1027 ãîä è 1087)   
        Delay(1500)
        Executejavascript(#web_1,"Ñîçäàòü Ìåñòî Ìàðê","idles Beach","")  
     EndSelect 
   EndIf         
  Until Event = #PB_Event_CloseWindow
EndIf
Puis créez un fichier html nomé "google.html" et copier collé ce code.

Code : Tout sélectionner

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" /> 
   <head> 
   <title>Bonjour Google Earth!</title> 
   <!-- *** Replace the key below below With your own API key, available at http://code.google.com/apis/maps/signup.html *** -->
   <script src="http://www.google.com/jsapi?key=ABQIAAAAwbkbZLyhsmTCWXbTcjbgbRSzHs7K5SvaUdm8ua-Xxy_-2dYwMxQMhnagaawTo7L1FE1-amhuQxIlXw"></script>

<script>
   google.load("earth", "1");
  var ge = null;
   function init() { 
   google.earth.createInstance("map3d", initCallback, failureCallback);
   }
   function initCallback(object) { 
   ge = object; 
   ge.getWindow().setVisibility(true); 
   }
   function failureCallback(object) { 
   }
</script>
    
</head>
   <body onload='init()' id='body'>
   <center> 
   <div id='map3d_container'  style='border: 1px solid silver; height: 600px; width: 800px;'>
   <div id='map3d' style='height: 100%;'></div> 
   </div>
   <div id='options_container'>
    <form name="options" action='javascript:updateOptions();'>
      <input type="checkbox" onclick='updateOptions()' name="statusbar" checked />Altitude&nbsp;
      <input type="checkbox" onclick='updateOptions()' name="nav" />Commandes zoom&nbsp;
      <input type="checkbox" onclick='updateOptions()' name="grid" />Grille &nbsp;
      <input type="checkbox" onclick='updateOptions()' name="overview" />Mini carte&nbsp;
      <input type="checkbox" onclick='updateOptions()' name="scaleLegend" />Légende échelle&nbsp;
      <input type="checkbox" onclick='updateOptions()' name="atmosphere" checked />Atmosphère&nbsp;
      <input type="checkbox" onclick='updateOptions()' name="mouseNav" checked />Transition&nbsp;
    </form>
  </div>
   </center>

<!---------------------Script Navigation------------------->
<script type="text/javascript">
google.load("earth", "1");
var ge = null;
function init() {
  google.earth.createInstance("map3d", initCB, failureCB);
}
function initCB(object) {
  ge = object;
  ge.getWindow().setVisibility(true);
  updateOptions();
}
function failureCB(object) {
}
function updateOptions() {
  var options = ge.getOptions();
  var form = document.options;
  options.setStatusBarVisibility(form.statusbar.checked);
  options.setGridVisibility(form.grid.checked);
  options.setOverviewMapVisibility(form.overview.checked);
  options.setScaleLegendVisibility(form.scaleLegend.checked);
  options.setAtmosphereVisibility(form.atmosphere.checked);
  options.setMouseNavigationEnabled(form.mouseNav.checked);
  if (form.nav.checked) {
    ge.getNavigationControl().setVisibility(ge.VISIBILITY_SHOW);
  } else {
    ge.getNavigationControl().setVisibility(ge.VISIBILITY_HIDE);
  }
}
</script>
<!-------------------------------------------------------------------- -->


<script type="text/javascript">
   var counter;
   function addToLineString(lineString, lat, lng, latOffset, lngOffset) { 
   lineString.getCoordinates().pushLatLngAlt(lat + latOffset, lng + lngOffset, 0); 
   }
   function CreateZigZag() { 
   var lookAt = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND); 
   var lat = lookAt.getLatitude(); 
   var lng = lookAt.getLongitude(); 
   var lineStringPlacemark = ge.createPlacemark(''); 
   var lineString = ge.createLineString(''); 
   lineStringPlacemark.setGeometry(lineString); 
   lineString.setTessellate(true); 
    
   addToLineString(lineString, lat, lng,   0,   0, 0); 
   addToLineString(lineString, lat, lng, 1.5,  .5, 0); 
   addToLineString(lineString, lat, lng,   0, 1.0, 0); 
   addToLineString(lineString, lat, lng, 1.5, 1.5, 0); 
   addToLineString(lineString, lat, lng,   0, 2.0, 0); 
   addToLineString(lineString, lat, lng, 1.5, 2.5, 0); 
   addToLineString(lineString, lat, lng,   0, 3.0, 0);
   addToLineString(lineString, lat, lng, 1.5, 3.5, 0); 
   addToLineString(lineString, lat, lng,   0, 4.0, 0); 
   addToLineString(lineString, lat, lng, 1.5, 4.5, 0); 
    
   ge.getFeatures().appendChild(lineStringPlacemark); 
   } 
    
   function CreatePlaceMark(strname) { 
    
   var placemark = ge.createPlacemark(''); 
   placemark.setName(strname); 
   ge.getFeatures().appendChild(placemark);
    
   // Create style Map For placemark 
   var normal = ge.createIcon(''); 
   normal.setHref('http://maps.google.com/mapfiles/kml/paddle/red-circle.png'); 
   var iconNormal = ge.createStyle(''); 
   iconNormal.getIconStyle().setIcon(normal); 
   var highlight = ge.createIcon(''); 
   //highlight.setHref('http://maps.google.com/mapfiles/kml/paddle/red-circle.png');
   highlight.setHref('http://gregcookland.com/journal/uploaded_images/picHasselHoff-747711.jpg'); 
   var iconHighlight = ge.createStyle(''); 
   iconHighlight.getIconStyle().setIcon(highlight);
   var styleMap = ge.createStyleMap(''); 
   styleMap.setNormalStyle(iconNormal); 
   styleMap.setHighlightStyle(iconHighlight); 
   placemark.setStyleSelector(styleMap); 
    
   // Create point 
   var la = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND); 
   var point = ge.createPoint(''); 
   point.setLatitude(la.getLatitude()); 
   point.setLongitude(la.getLongitude()); 
   placemark.setGeometry(point); 
    
   counter++; 
   }
   function LookAt(lat, long, alt) { 
   
   var lookAt = ge.getView().copyAsCamera(ge.ALTITUDE_RELATIVE_TO_GROUND); 
   lookAt.setLatitude(lat);
   lookAt.setLongitude(long); 
   lookAt.setAltitude(alt); 
   ge.getView().setAbstractView(lookAt);
   
   Return =   (lat+" "+long+" "+alt); 
   }
</script>
    
</body>
</html>
Placer les deux fichier dans le même répertoire pour que ca fonctionne.
Avatar de l’utilisateur
kernadec
Messages : 1606
Inscription : ven. 25/avr./2008 11:14

Re: Google Maps et OpenStreetMap

Message par kernadec »

bonjour MetalOS
pour ce code posté par "Idle" l' URL est indiquée en tête du code.
je n'avais pas compris qu il fallait utiliser à la compilation le mode Unicode

donc je l'avais modifié pour un mode sans Unicode avec la ville ou j'habite :mrgreen:

Cordialement
Avatar de l’utilisateur
MetalOS
Messages : 1510
Inscription : mar. 20/juin/2006 22:17
Localisation : Lorraine
Contact :

Re: Google Maps et OpenStreetMap

Message par MetalOS »

Sa montre comment interagir avec le plugins Google earth. Je trouve ce code très intéressant peut être voir à exploiter cette piste pour remplacer ma carte maron dans mon autre post ;-)
Répondre