如何在没有标记的情况下制作Google Map Place Search Box?

时间:2015-12-12 11:26:38

标签: javascript google-maps laravel google-maps-api-3 google-maps-markers

这是Google地图搜索功能的代码片段,用于搜索特定位置。如何制作谷歌地图搜索功能,无需标记即可搜索特定位置。我研究了谷歌地图搜索框,但到目前为止,即使在Google Developers Website中,我研究的大部分标记都无法找到。

 var searchBox = new google.maps.places.SearchBox(document.getElementById('searchmap'));

 google.maps.event.addListener(searchBox,'places_changed',function() {

    var places = searchBox.getPlaces();
    var bounds = new google.maps.LatLngBounds();
    var i, place;

    for (var i = 0; place= place[i]; i++) {
        bounds.extend(place.geometry.location);
        marker.setPosition(place.geometry.location);

        }
        map.fitBounds(bounds);
        map.setZoom(15);
    });
 google.maps.event.addListener(marker,'position_changed', function(){

    var lat = marker.getPosition().lat();
    var lng = marker.getPosition().lat();

    $('#lat').val(lat);
    $('#lat').val(lat);
 });

1 个答案:

答案 0 :(得分:1)

以下是来自Places search box页面的已修改示例,其中演示了如何利用Google地方自动填充功能(删除使用标记标记地点的依赖关系)

function initAutocomplete() {
    var map = new google.maps.Map(document.getElementById('map'), {
        center: { lat: -33.8688, lng: 151.2195 },
        zoom: 13,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });


    var input = document.getElementById('searchmap');
    var searchBox = new google.maps.places.SearchBox(input);
    map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

  
    searchBox.addListener('places_changed', function () {
        var places = searchBox.getPlaces();

        if (places.length == 0) {
            return;
        }
   
        var bounds = new google.maps.LatLngBounds();
        places.forEach(function (place) {
           
            if (place.geometry.viewport) {
                // Only geocodes have viewport.
                bounds.union(place.geometry.viewport);
            } else {
                bounds.extend(place.geometry.location);
            }
        });
        map.fitBounds(bounds);
    });
    
}
html, body {
    height: 100%;
    margin: 0;
    padding: 0;
}

#map {
    height: 100%;
}

.controls {
    margin-top: 10px;
    border: 1px solid transparent;
    border-radius: 2px 0 0 2px;
    box-sizing: border-box;
    -moz-box-sizing: border-box;
    height: 32px;
    outline: none;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}

#searchmap {
    background-color: #fff;
    font-family: Roboto;
    font-size: 15px;
    font-weight: 300;
    margin-left: 12px;
    padding: 0 11px 0 13px;
    text-overflow: ellipsis;
    width: 300px;
}

#searchmap:focus {
    border-color: #4d90fe;
}
<input id="searchmap" class="controls" type="text" placeholder="Search Box">
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&callback=initAutocomplete"
            async defer></script>