2013-10-17 34 views
1

我已經實現了谷歌地圖API搜索 直到自動生成的位置,但我想這樣的設施由我能得到確切位置我的代碼工作正常通過僅提供城市名稱而不是整個格式字符串。如何自動按城市在谷歌地圖API的名稱在PHP填寫州和國家

對於前:

請檢查該圖像http://demo.ncryptedprojects.com/nct_bnb_clone_new/Untitled.png

我在快樂的搜索框和谷歌地圖API輸入城市名孟買檢索下拉所有的價值,當有人不選擇任何值從下拉菜單,然後直接按城市名後進入我不能得到精確搜索城市孟買地圖 所以,我究竟想要做的是,當有人進入城市名,然後搜索它會自動從下拉像搜索第一次出現「孟買馬哈拉施特拉邦,印度」

HTML表單

<input name="location" id="location" type="text"/> 

谷歌地圖API

<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script> 

$(function() { 
      var e; 
      e = $('.search-form input[name="location"]')[0]; 
      return new google.maps.places.Autocomplete(e, { 
       types: ["geocode"] 
      }) 

    }); 
+0

檢查http://stackoverflow.com/questions/14601655/google-places-autocomplete-pick-first-result-on-enter-key以及在該問題中發佈的其他鏈接 – Rohit

回答

0

這是棘手,因爲默認情況下,谷歌的地方將查找地點附近的地圖的中心,無論該建議在下拉。

因此,您必須從下拉列表中找到第一條建議,即document.querySelector('.pac-item') - 提取位置並使用地理編碼器查找該位置的緯度。

代碼提取的位置:

function extractLocation(item) { 
    var text = item.innerText || item.textContent; 
    var upper = text.toUpperCase(); 
    var result=''; 
    for (var i=0;i<text.length;i++) { 
     if (text[i]==upper[i]) { 
      result+=' '; 
     } 
     result+=text[i]; 
    } 
    return result; 
} 

在搜索框輸入,選擇第一個建議,提取位置,查找的地理編碼器和地方標誌經緯度:

input.onkeyup = function(e) { 
    var code = (e.keyCode ? e.keyCode : e.which); 
    var places = searchBox.getPlaces(); 
    if (code == 13 && places!=[]) { 
    var firstSuggestion = document.querySelector('.pac-item'); 
    var query = extractLocation(firstSuggestion); 
    geocoder.geocode({"address":query }, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      clearMarkers(); 
      var latLng = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng()); 
      var marker = new google.maps.Marker({ 
      map: map, 
      title: results[0].address_components[0].long_name, 
      position: latLng, 
      }); 
      markers.push(marker); 
      map.setCenter(latLng); 
      map.setZoom(10); 
     } 
    }); 
    } 
} 

工作小提琴 - >http://jsfiddle.net/cdnT8/

+0

感謝您的幫助 –

相關問題