2013-03-13 2 views
1

У меня есть ответ JSON со следующего URL:Как декодировать полилиний из Google Maps Direction API в PHP

http://maps.googleapis.com/maps/api/directions/json?origin=Chicago,IL&destination=Los%20Angeles,CA&sensor=false

JSON путь routes[x].legs[y].steps[z].polyline.points?:

«AZQ ~ КЛОХ {uOAlB Jb ????^P P B @ V @ |? J @ фА хА @ хА ч @ B F @ tā @ XD @ ч @ BNA |????? A @ гв @ F @ d @@ v @ ? А д @ AZEzA BIjB @Cx @ @ EzAAlC F F T B F @ DhHBhD @ R L @ R |?????????? CCpDAj @ E | DGnDKzCCb @ OtBa @ rFGfAAb @ @? FAp @? ADbJD|[email protected]@@@[email protected]@@[email protected][email protected]@^@[email protected][email protected] F? VC? HB? @BpM? @? J @@ p @@ | KB ~ Q @ pFBbHBvF @ z @? F @@ jB? NA @ z @ DzD @ VJ ~ CLfC \ | E? B ? @ HnANtAVpDRpCLbB^dFTxC @ LZvDF^HrALlCH EB|H?DBpEB~V?^BhDJ R? @@ \? ~ A? NABrL? @? JD @ vD @ vA? H @? BLx [? X @? B? \? F @ pA? H @ D ~ H? @ Bz @ Dr @ RbCLfA \ rBPv @@@ T ~ @ t @ bCPf @ z @ xBd @ rAf @ dB \ zAN ~ @ PjAT ~ BFrADxAH [email protected][email protected][email protected][email protected]@[email protected]^F|[email protected]@D|[email protected][email protected][email protected] C? | A? v @ AlBCdA? r @ EjEC | BItEMdGEtAIfEI | BKzDOzGEjCCl @? @ MnDW [email protected][email protected]|[[email protected]@[email protected][email protected] AYjFIzAWxDQpCYpEAFItACt @ S ~ C] | GSlEMnCMtCGdAKlBQxDg @ bLAT? BKrCAn @ Ad @? X @? P @? J? @ @ LA @ z @ BbABn @ Bt @@@[email protected]^L AT BP AP ~ @ Z ~ ALn @? @@ Fd @ | BjAfGd @ дДД @ | D \ bFDf @ D ~ @@ F @ B |? @@ XCJ P?dBB EDtE @ bADlAR [email protected]@F @@[email protected][email protected][email protected]? ADhLBbD @ х @ F @ ~ C dCNbTDrIBxDLbO @ ~ AV [email protected]][email protected][email protected]@[email protected]^ FHX @ H | @@bDPxAZpCTbDN DBlC @ J @@ J @ BhAHhLBvC? р @ BLB? jAAfAAx @ C @MzDM|[email protected]@pF]fB][email protected]@[email protected]@[email protected][email protected]@[email protected][email protected]@W|@[email protected][email protected] AOpAKfAEp @ Gz @ Cb @ GpACZAVAh @ Ad @ AX? е @ в @ КПБ»

Я хочу, чтобы декодировать строку Ломаная точек на Lat Long значения вернулся b y вышеупомянутый URL-адрес, используя PHP.

Я нашел некоторые результаты в Java и Objective C, но мне это нужно в PHP.

+2

Вы ищете что-то [подобное] (https://github.com/emcconville/google-map-polyline-encoding-tool)? – j0k

+0

да, я думаю, поэтому проверю, спасибо –

ответ

4

Вы можете посмотреть на этот репозиторий на Github: Google Maps Polyline Encoding Tool

Простой PHP класс для преобразования полилинии в кодированной строки для Google Maps.

2
<?php 

# Do steps 1-11 given here 
# https://developers.google.com/maps/documentation/utilities/polylinealgorithm 
# in reverse order and inverted (i.e. left shift -> right shift, add -> subtract) 

$string = "udgiEctkwIldeRe}|[email protected]|flA`nrvApihC"; 
# Step 11) unpack the string as unsigned char 'C' 
$byte_array = array_merge(unpack('C*', $string)); 
$results = array(); 

$index = 0; # tracks which char in $byte_array 
do { 
    $shift = 0; 
    $result = 0; 
    do { 
    $char = $byte_array[$index] - 63; # Step 10 
    # Steps 9-5 
    # get the least significat 5 bits from the byte 
    # and bitwise-or it into the result 
    $result |= ($char & 0x1F) << (5 * $shift); 
    $shift++; $index++; 
    } while ($char >= 0x20); # Step 8 most significant bit in each six bit chunk 
    # is set to 1 if there is a chunk after it and zero if it's the last one 
    # so if char is less than 0x20 (0b100000), then it is the last chunk in that num 

    # Step 3-5) sign will be stored in least significant bit, if it's one, then 
    # the original value was negated per step 5, so negate again 
    if ($result & 1) 
    $result = ~$result; 
    # Step 4-1) shift off the sign bit by right-shifting and multiply by 1E-5 
    $result = ($result >> 1) * 0.00001; 
    $results[] = $result; 
} while ($index < count($byte_array)); 

# to save space, lat/lons are deltas from the one that preceded them, so we need to 
# adjust all the lat/lon pairs after the first pair 
for ($i = 2; $i < count($results); $i++) { 
    $results[$i] += $results[$i - 2]; 
} 

# chunk the array into pairs of lat/lon values 
var_dump(array_chunk($results, 2)); 

# Test correctness by using Google's polylineutility here: 
# https://developers.google.com/maps/documentation/utilities/polylineutility 

?> 
5

Реализация Python

Это не в PHP, но этот поток в верхней части результатов поиска, если вы хотите, чтобы декодировать полилинии строки из Google Maps. Если кому-то это понадобится (как и я), вот реализация Python для декодирования строк полилинии. Это портировано из версии Mapbox JavaScript; подробнее узнать на моем repo page.

def decode_polyline(polyline_str): 
    index, lat, lng = 0, 0, 0 
    coordinates = [] 
    changes = {'latitude': 0, 'longitude': 0} 

    # Coordinates have variable length when encoded, so just keep 
    # track of whether we've hit the end of the string. In each 
    # while loop iteration, a single coordinate is decoded. 
    while index < len(polyline_str): 
     # Gather lat/lon changes, store them in a dictionary to apply them later 
     for unit in ['latitude', 'longitude']: 
      shift, result = 0, 0 

      while True: 
       byte = ord(polyline_str[index]) - 63 
       index+=1 
       result |= (byte & 0x1f) << shift 
       shift += 5 
       if not byte >= 0x20: 
        break 

      if (result & 1): 
       changes[unit] = ~(result >> 1) 
      else: 
       changes[unit] = (result >> 1) 

     lat += changes['latitude'] 
     lng += changes['longitude'] 

     coordinates.append((lat/100000.0, lng/100000.0)) 

    return coordinates 
+0

большое спасибо! ..... – morpheus

+0

Вместо этого вы можете использовать библиотеку полилинии (https://pypi.python.org/pypi/polyline/)! – Shayn

0

Самое простое решение этой проблемы ..

Вот Link на Github Репо, который включает в себя класс для кодирования/декодирования. Он также имеет простейшее возможное описание использования.

Примечание: я должен был изменить класс немного для декодирования полилинию функции decodeValue, последнюю строку в то время как цикл. Я имел заменить 100000 с 1000000

$points[] = array('x' => $lat/1000000, 'y' => $lng/1000000); 
Смежные вопросы