2014-03-24 34 views
1

我有一個搜索框和一張地圖,所以當用戶在搜索框中寫入地點時,地圖應該移動到用戶選擇的位置。將字符串轉換爲位置Google地圖

,我也與此代碼:

var input = document.getElementById('addressInput'); 
var searchBox = new google.maps.places.SearchBox((input)); 
var places = searchBox.getPlaces(); 
google.maps.event.addListener(searchBox, 'places_changed', function() { 
    places = searchBox.getPlaces(); 
    if (places[0].geometry.viewport) { 
     map.fitBounds(places[0].geometry.viewport); 
    } else { 
     map.setCenter(places[0].geometry.location); 
     map.setZoom(17); // Why 17? Because it looks good. 
    } 
}); 

因此,當用戶改變發生在我的搜索框,一切工作正常

問題是,當我到達包含地圖的頁面第一次,因爲我已經有一個像「魔術」或'芝加哥,伊利諾伊州的一個字符串(我從另一個頁面此字符串),我這個值放到搜索框

document.getElementById('addressInput').value='Orlando'; 

但我沒有得到地方細節,因爲不是一個place_changed事件

如何將該字符串轉換成一個地方?

回答

1

它不適合你的原因是(我們沒有看到實際的代碼),你試圖在谷歌地圖的所有部分完成加載之前進行搜索。將您的代碼放在idle事件中:

google.maps.event.addListenerOnce(map, 'idle', function(){ 
    input.value='Orlando'; 
    input.focus(); 
}); 

它可以工作。見小提琴 - >http://jsfiddle.net/2L5t3/


更新。如果您想自動搜索自動選擇第一個搜索結果/預測,我建議您在頁面加載上使用google.maps.places.PlacesService。更改空閒功能,:

google.maps.event.addListenerOnce(map, 'idle', function(){ 
    var request = { 
     query: 'Orlando' 
    }; 

    service = new google.maps.places.PlacesService(map); 
    service.textSearch(request, callback); 

    function callback(results, status) { 
     if (status == google.maps.places.PlacesServiceStatus.OK) { 
      //grab the first item, Orlando, Florida, USA 
      var place = results[0]; 
      input.value = place.formatted_address; 
      map.setCenter(place.geometry.location); 
     } 
    } 
}); 

查看 - >http://jsfiddle.net/j2Kn3/

searchBox/places_changed工作正常之後。這隻能通過pageload調用,並返回相同的經緯度,就像搜索奧蘭多一樣,並以用戶身份抓取第一個預測。

我嘗試了100種方式,但似乎不可能在沒有用戶操作的情況下選擇.pac-container上的第一項,甚至嘗試發送事件 - 沒有運氣。

+0

感謝您的回覆,我看到了您的代碼,但以這種方式將奧蘭多放入搜索框中,但地圖停留在悉尼,並且不會更改爲奧蘭多?我可以把中心換成奧蘭多嗎? – Simo

+0

@Simo,對不起 - 我誤解了。以爲你只是想激活搜索。 – davidkonrad

相關問題