Italian google maps - Percorso tra due punti

ken87

Active Member
Licensed User
Longtime User
Ciao si parlo di Api Google map allora ho provato questo codice:

B4X:
#Region  Project Attributes
   #ApplicationLabel: mappa
   #VersionCode: 1
   #VersionName:
   'SupportedOrientations possible values: unspecified, landscape or portrait.
   #SupportedOrientations: unspecified
   #CanInstallToExternalStorage: False
    #AdditionalJar: com.google.android.gms:play-services-maps
   

#End Region

#Region  Activity Attributes
   #FullScreen: False
   #IncludeTitle: True
#End Region

'Activity module
Sub Process_Globals
    Type MapPointItem (dLatitude As Double, dLongitude As Double, iPassed As Int)
End Sub

Sub Globals
    Private gmap As GoogleMap
    Dim cp As CameraPosition
    Private MapFragment1 As MapFragment
    Private localsat As GoogleMapView
    Dim point As LatLng
    Dim gextra As GoogleMapsExtras
    Private lm As LocationManager
    Dim l1, l2,l3,l4,l5,l6,l7 As LatLng
    Private PolyRoute As Polyline
    Private Point1, Point2 As LatLng
   
   
   

   
    Private traccia As Button
    Private cancella As Button
End Sub

Sub Activity_Create(FirstTime As Boolean)
   
    Activity.LoadLayout("maps")
    Point1.Initialize(39.0632229, 8.4546907)
    Point2.Initialize(39.305575,8.522429099999954)
    If MapFragment1.IsGooglePlayServicesAvailable = False Then
        ToastMessageShow("Please install Google Play Services.", True)
    End If
   
End Sub

Sub MapFragment1_Ready
   
    gmap = MapFragment1.GetMap
       
    If gmap.IsInitialized Then
   
   
    Dim cp As CameraPosition
       
    gmap.MapType = gmap.MAP_TYPE_NORMAL
                       
    cp.Initialize(39.0632229,8.4546907, 18)
        gmap.AnimateCamera(cp)
   
        gmap.MapType = gmap.MAP_TYPE_NORMAL
                       
        cp.Initialize(39.0632229,8.4546907, 10)
        gmap.AnimateCamera(cp)
       
        gmap.AddMarker2(39.0632229, 8.4546907, "prova", gmap.HUE_ORANGE)
        gmap.AddMarker2(39.305575,8.522429099999954, "prova2", gmap.HUE_AZURE)
   
       
    Else
        ToastMessageShow("Error initializing map.", True)
    End If
   
End Sub

Sub Location_LocationChanged (Longitude As Double, Latitude As Double, Altitude As Double, Accuracy As Float, Bearing As Float, Provider As String, Speed As Float, Time As Long)
   
    Msgbox("Longitude: " & Longitude & CRLF & "Latitude: " & Latitude & CRLF & "Altitude: " & Altitude & CRLF & "Accuracy: " & Accuracy & CRLF & "Bearing: " & Bearing & CRLF & "Speed: " & Speed,"Location")
    Msgbox (Longitude,Longitude)

End Sub

Sub Button1_Click
    Msgbox (gmap.MyLocation.Latitude,"")
    Msgbox (gmap.MyLocation.Longitude,"")
End Sub

Sub traccia_Click
    Dim Job As HttpJob
    Job.Initialize("RequestRoute", Me)
   
    Dim sb As StringBuilder
    sb.Initialize
    sb.Append("http://maps.googleapis.com/maps/api/directions/json?origin=")
    sb.Append(Point1.Latitude)
    sb.Append(",")
    sb.Append(Point1.Longitude)
    sb.Append("&destination=")
    sb.Append(Point2.Latitude)
    sb.Append(",")
    sb.Append(Point2.Longitude)
    sb.Append("&sensor=True&mode=walking")
   
    Log("Request: " & sb.ToString)
   
    Job.Download(sb.ToString)

End Sub

Sub JobDone(Job As HttpJob)
    If Job.Success Then
        Select Job.JobName
            Case "RequestRoute"
                TraceRoute(Job.GetString)
        End Select
    End If  
End Sub

Sub TraceRoute(JSON As String) ' Traccia il tracciato
    Dim parser As JSONParser : parser.Initialize(JSON)
    Dim routes, listMpi, legs, steps As List
    Dim root, bounds, southwest, northeast, polylineMap As Map : root = parser.NextObject
    Dim swlat, swlng, nelat, nelng As Double
    Dim sw, ne As LatLng
    Dim posBounds As LatLngBounds
   
    If root.Get("status") = "OK" Then
        routes = root.Get("routes")
        listMpi.Initialize
        For Each colroutes As Map In routes
            bounds = colroutes.Get("bounds")
           
            southwest = bounds.Get("southwest")
            swlat = southwest.Get("lat")
            swlng = southwest.Get("lng")
            sw.Initialize(swlat, swlng)
           
            northeast = bounds.Get("northeast")
            nelat = northeast.Get("lat")
            nelng = northeast.Get("lng")
            ne.Initialize(nelat, nelng)
            posBounds.Initialize(sw, ne)
            SetZoom(100, posBounds)
           
            legs = colroutes.Get("legs")
            For Each collegs As Map In legs
                steps = collegs.Get("steps")
                For Each colsteps As Map In steps
                    polylineMap = colsteps.Get("polyline")
                    'Log("points: " & polylineMap.Get("points"))
                    decodePoly(polylineMap.Get("points"), listMpi)
                    'MapsDecodePolyline (polylineMap.Get("points"), listMpi)
                Next
            Next
           
            Dim mpiCurrent As MapPointItem
            Dim latlngPoint As LatLng
            Dim listPoints As List : listPoints.Initialize
            For i = 0 To listMpi.Size - 1
                mpiCurrent = listMpi.Get(i)
                latlngPoint.Initialize(mpiCurrent.dLatitude, mpiCurrent.dLongitude)
                listPoints.Add(latlngPoint)
            Next
           
            If PolyRoute.IsInitialized Then PolyRoute.Remove
            PolyRoute = gmap.AddPolyline
            PolyRoute.Color = Colors.Red
            PolyRoute.Points = listPoints
           
            For i = 0 To listPoints.Size - 1
                'Log("listPoints: " & listPoints.Get(i))
            Next
            listPoints.Clear
        Next
    Else
        Log("Status: " & root.Get("status"))
    End If
End Sub








Sub decodePoly(encoded As String, poly As List)
    Dim b, index, lat, lng, dlat, dlng, flat, flng, shift, result As Int : index = 0 : lat = 0 : lng = 0
   
    Do While index < encoded.Length
        shift = 0 : result = 0
        Do While True
            b = Asc(encoded.SubString2(index, index + 1)) - 63 : index = index + 1
            result = Bit.Or(result, Bit.ShiftLeft( Bit.And( b, 0x1f), shift))
            shift = shift + 5
            If b < 0x20 Then Exit
        Loop
       
        If Bit.And(result, 1) = 1 Then
            dlat = Bit.Not(Bit.ShiftRight(result, 1))
        Else
            dlat = Bit.ShiftRight(result, 1)
        End If
        lat = lat + dlat
       
        shift = 0 : result = 0
        Do While True
            b = Asc(encoded.SubString2(index, index + 1)) - 63 : index = index + 1
            result = Bit.Or(result, Bit.ShiftLeft(Bit.And(b, 0x1f), shift))
            shift = shift + 5
            If b < 0x20 Then Exit
        Loop
       
        If Bit.And(result, 1) = 1 Then
            dlng = Bit.Not(Bit.ShiftRight(result, 1))
        Else
            dlng = Bit.ShiftRight(result, 1)
        End If
        lng = lng + dlng
        flat = lat
        flng = lng
       
        Dim mpiCurrent As MapPointItem
        mpiCurrent.Initialize
        mpiCurrent.iPassed = 0
        mpiCurrent.dLatitude = flat / 1E5
        mpiCurrent.dLongitude = flng / 1E5
        poly.Add(mpiCurrent)
       
    Loop
   
End Sub


Sub MapsDecodePolyline(encoded As String, poly As List)
    Log("MapsDecodePolyline")
   
    Dim index As Int
    Dim lat As Int
    Dim lng As Int
    Dim fLat As Float
    Dim fLng As Float
    Dim b As Int
    Dim shift As Int
    Dim result As Int
    Dim dlat As Int
    Dim dlng As Int
    Dim p As LatLng
    Dim i As Int
    Dim l As LatLng

    index = 0 : lat = 0 : lng = 0
    Do While index < encoded.Length
        shift = 0 : result = 0
        Do While True
            b = Asc(encoded.SubString2(index, index + 1)) - 63 : index = index + 1
            result = Bit.Or(result, Bit.ShiftLeft(Bit.And(b, 0x1f), shift))
            shift = shift + 5
            If b < 0x20 Then Exit
        Loop
       
        If Bit.And(result, 1) = 1 Then
            dlat = Bit.Not(Bit.ShiftRight(result, 1))
        Else
            dlat = Bit.ShiftRight(result, 1)
        End If
        lat = lat + dlat
        shift = 0 : result = 0
        Do While True
            b = Asc(encoded.SubString2(index, index + 1)) - 63 : index = index + 1
            result = Bit.Or(result, Bit.ShiftLeft(Bit.And(b, 0x1f), shift))
            shift = shift + 5
            If b < 0x20 Then Exit
        Loop
       
        If Bit.And(result, 1) = 1 Then
            dlng = Bit.Not(Bit.ShiftRight(result, 1))
        Else
            dlng = Bit.ShiftRight(result, 1)
        End If
        lng = lng + dlng
        fLat = lat
        fLng = lng
       
        Dim mpiCurrent As MapPointItem
        mpiCurrent.Initialize
        mpiCurrent.iPassed = 0
        mpiCurrent.dLatitude = fLat / 100000
        mpiCurrent.dLongitude = fLng / 100000
        poly.add(mpiCurrent)
    Loop
End Sub

   


#Region Zoom
Sub SetZoom (Padding As Int, posBounds As LatLngBounds)
    Dim sw, ne As LatLng
    Dim cp As CameraPosition
    sw.Initialize(posBounds.SouthWest.Latitude, posBounds.SouthWest.Longitude)
    ne.Initialize(posBounds.NorthEast.Latitude, posBounds.NorthEast.Longitude)
    Try
        cp.Initialize(posBounds.Center.Latitude, posBounds.Center.Longitude, gmap.CameraPosition.Zoom)
        gmap.AnimateCamera(cp)
        ZoomToBoundaries(gmap, sw, ne, Padding)
    Catch
        Log(LastException.Message)
    End Try
End Sub

'SouthWest, NorthEast - the visible box
'Padding - Padding from the map edges
Sub ZoomToBoundaries (gm As GoogleMap, SouthWest As LatLng, NorthEast As LatLng, Padding As Int)
    Dim r As Reflector
    Dim CameraRefresh As Object
   
    r.Target = r.CreateObject2("com.google.android.gms.maps.model.LatLngBounds", _
                            Array As Object(SouthWest, NorthEast), _
                            Array As String("com.google.android.gms.maps.model.LatLng", _
                                            "com.google.android.gms.maps.model.LatLng"))
    CameraRefresh = r.RunStaticMethod("com.google.android.gms.maps.CameraUpdateFactory", "newLatLngBounds", _
                                    Array As Object(r.Target, Padding), _
                                    Array As String("com.google.android.gms.maps.model.LatLngBounds", _
                                                    "java.lang.int"))
    r.Target = gm
    r.RunMethod4("moveCamera", Array As Object(CameraRefresh), Array As String("com.google.android.gms.maps.CameraUpdate"))
End Sub
#End Region






Sub posiziona_Click
    gmap.Clear
    Dim cp As CameraPosition
       
    gmap.MapType = gmap.MAP_TYPE_NORMAL
                       
    'cp.Initialize(39.0632229,8.4546907, 18)
    'gmap.AnimateCamera(cp)
       
    gmap.AddMarker2(39.0632229, 8.4546907, "prova", gmap.HUE_ORANGE)
    gmap.AddMarker2(39.305575,8.522429099999954, "prova2", gmap.HUE_AZURE)
   
End Sub
Quando premo il tasto traccia ,alcune volte funziona bene creando la traccia tra due punti
alcune volte il Json Fallisce restituendo i log sotto allegato


Request: http://maps.googleapis.com/maps/api...75,8.522429099999954&sensor=True&mode=walking
Status: OVER_QUERY_LIMIT
B4X:
sub TraceRoute(JSON As String) ' Traccia il tracciato
    Dim parser As JSONParser : parser.Initialize(JSON)
    Dim routes, listMpi, legs, steps As List
    Dim root, bounds, southwest, northeast, polylineMap As Map : root = parser.NextObject
    Dim swlat, swlng, nelat, nelng As Double
    Dim sw, ne As LatLng
    Dim posBounds As LatLngBounds
   
    If root.Get("status") = "OK" Then

Non riuscendo a superare " root.Get("status") = "OK"
Perchè si verifica questo errore?
 
Last edited:

ken87

Active Member
Licensed User
Longtime User
La chiave c'e ho . L'ho registrata dal sito, il codice su esposto gira e funziona ovviamante nel mainifest ho messo la mia chiave abilitata sia per android che per web sia per poter ricavare il percoso.
Il problema e che alcine volte mi crea il percoso alre volte restituisce OVER_QUERY_LIMIT
 

ken87

Active Member
Licensed User
Longtime User
Ciao la chiave l'ho registrata e funziona di per visualizzare la mappa, sia per tracciare il percorso.
Il problema che alcune volte recuperara i file Jison e traccia il percorso altre volte va in errore vedi allegati
 

Attachments

  • sped2.jpg
    sped2.jpg
    167.4 KB · Views: 240
  • sped3.jpg
    sped3.jpg
    177.4 KB · Views: 244

marcick

Well-Known Member
Licensed User
Longtime User
a me non sembra che nella richiesta tu dichiari la chiave

B4X:
  Dim sb As StringBuilder
    sb.Initialize
    sb.Append("http://maps.googleapis.com/maps/api/directions/json?origin=")
    sb.Append(Point1.Latitude)
    sb.Append(",")
    sb.Append(Point1.Longitude)
    sb.Append("&destination=")
    sb.Append(Point2.Latitude)
    sb.Append(",")
    sb.Append(Point2.Longitude)
    sb.Append("&sensor=True&mode=walking")
 
    Log("Request: " & sb.ToString)
 
    Job.Download(sb.ToString)

Manca un sb.Append("&key=" & APIKEY)
 
Last edited:

ken87

Active Member
Licensed User
Longtime User
Ciao, la chiave è memorizzata sul Manifest.

B4X:
AddApplicationText(<meta-data
    android:name="com.google.android.maps.v2.API_KEY"
    android:value="AIzaxxxxxxxxxxxxx-
xxxxxxxxxxxxxxxxx" />
<meta-data android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version"
Al posto delle xx va messa quella abilitata da google.
Ho risolto, funziona.. una volta abilitata bisogna aspettare più di un giorno prima che funzioni sempre
Grazie mille
 

marcick

Well-Known Member
Licensed User
Longtime User
Mi spiace ma ancora non hai afferrato. La chiave sta nel manifest per potere visualizzare la mappa. Ma è diventata obbligatoria per ogni chiamata alle API via http. Se hai la bontà di guardare la documentazione che ti ho linkato lo vedi. Perché Google vuole contabilizzare l’utilizzo e chiederti soldi se superi la quota gratuita.
Il fatto che ti stia ancora funzionando non vuol dire nulla. Sono subentrate nuove regole. O ti adegui o avrai presto problemi. Poi fai come ti pare.
 

tmtube73

Active Member
Licensed User
A me serve poter tracciare una linea fra 2 punti sulla mappa e conoscerne la lunghezza, è possibile?

Grazie.
 
Top