2

検索に Google マップ API を実装しました。私のコードは自動生成された場所まで正常に動作していますが、書式文字列全体ではなく都市名のみを提供することで正確な場所を取得できる機能が必要です。

例:

この画像を確認してくださいhttp://demo.ncryptedprojects.com/nct_bnb_clone_new/Untitled.png

検索ボックスにムンバイという都市名を入力すると、Google マップ API がドロップダウンのすべての値を取得します。誰かがドロップダウンから値を選択せず​​、都市名の後に直接Enterキーを押すと、地図で都市ムンバイを正確に検索できません。私が正確にやりたいことは、誰かが都市名を入力して検索すると、「ムンバイ マハラシュトラ、インド」のようなドロップダウンから最初に出現したものを自動的に検索することです。

HTMLフォーム

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

Google マップ 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"]
            })

    });
4

1 に答える 1

0

デフォルトでは、ドロップダウンの提案に関係なく、Google Places は地図の中心近くの場所を検索するため、これは注意が必要です。

したがって、ドロップダウンから最初の提案を見つける必要があります。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/

于 2013-10-17T15:13:34.073 に答える