首页 > 解决方案 > 如何在 MapKit JS 中创建类似于 Google 的 Place Autocomplete 的自动完成查找

问题描述

我已经设法使用 Apple 的 MapKit JS 在网页上显示地图和路线,但由于缺少示例代码,我无法从文档中了解搜索和自动完成的工作原理。我已经尝试了所有可以搜索的搜索词,但似乎在任何地方都找不到任何示例。如果有人可以向我展示 MapKit JS 搜索/自动完成代码的示例,我可能会找出其余部分来连接类似于 Google 的 Places Autocomplete 的东西。

提前致谢。

标签: javascriptautocompletemapkit

解决方案


好的,我现在已经弄清楚并分享答案以造福他人。

使用 MapKit JS,您可以创建一个新的搜索对象,然后对该对象调用自动完成功能;所以:

let search = new mapkit.Search({ region: map.region });
search.autocomplete('searchterm', (error, data) => {
    if (error) {
        return;
    }
        // handle the results
    });
});

MapKit JS 将结果作为 data.results 中的对象发送回,包括:

coordinate.latitude
coordinate.longitude
displayLines ([0] contains the place name and [1] is the address)

因此,您只需遍历结果并构建一个列表。

并将所有这些放在一起:

首先让CSS使自动完成整洁:

<style>
    .mapSearchWrapper {
        position: relative;
    }
    .mapSearchInput {
        width: 100%;
        padding: 4px;
    }
    .mapSearchResults {
        display: none;
        position: absolute; 
        top: 20px; 
        left: 0px;
        z-index:9999;
        background: #FFFFFF; 
        border: 1px #CCCCCC solid;
        font-family: sans-serif;
    }
    .mapSearchResultsItem {
        padding: 4px;
        border-bottom: 1px #CCCCCC solid;
    }
    .mapSearchResultsItem:hover {
        background: #EEEEEE;
    }
</style>

然后是包含输入框、结果结果和实际地图的 HTML。

<div class="mapSearchWrapper">
    <input type="text" id="mapLookup" class="mapSearchInput">
    <div id="results" class="mapSearchResults">
    </div>
</div>

<div id="map"></div>

然后是真正的 JavaScript 让魔法发生。注意我已经加载了 JQuery,因此如果您使用此代码,您将需要该库。

<script type="text/javascript">
    // Initialise MapKit
    mapkit.init({
        authorizationCallback: function(done) {
        done('[REPLACE THIS WITH YOUR OWN TOKEN]');
        }
    });
    // Create an initial region. This also weights the search area 
    var myRegion = new mapkit.CoordinateRegion(
        new mapkit.Coordinate(55.9496320, -3.1866360),
        new mapkit.CoordinateSpan(0.05, 0.05)
    );
    // Create map on the id 'map'
    var map = new mapkit.Map("map");
    map.region = myRegion;
    // Listen for keyup in the input field
    $('#mapLookup').keyup(function(){
        // Make sure it's not a zero length string
        if($('#mapLookup').length>0) {
            let search = new mapkit.Search({ region: map.region });
            search.autocomplete($('#mapLookup').val(), (error, data) => {
                if (error) {
                    return;
                }
                // Unhide the result box
                $('#results').show();
                var results = "";
                // Loop through the results a build 
                data.results.forEach(function(result) {
                    if(result.coordinate) {
                        // Builds the HTML it'll display in the results. This includes the data in the attributes so it can be used later
                        results = results + '<div class="mapSearchResultsItem" data-title="' +result.displayLines[0] + '" data-latitude="'+result.coordinate.latitude+'" data-longitude="'+result.coordinate.longitude+'" data-address="'+result.displayLines[1]+'"><b>' + result.displayLines[0] + '</b> ' + result.displayLines[1] + '</div>';
                    }
                });
                // Display the results
                $('#results').html(results);
                // List for a click on an item we've just displayed
                $('.mapSearchResultsItem').click(function() {
                    // Get all the data - you might want to write this into form fields on your page to capture the data if this map is part of a form.
                    var latitude = $(this).data('latitude');
                    var longitude = $(this).data('longitude');
                    var title = $(this).data('title');
                    var address = $(this).data('address');
                    // Calc the new region
                    var myRegion = new mapkit.CoordinateRegion(
                        new mapkit.Coordinate(latitude, longitude),
                        new mapkit.CoordinateSpan(0.01, 0.01)
                    );
                    // Clean up the map of old searches
                    map.removeAnnotations(map.annotations);
                    map.region = myRegion;
                    // Add the new annotation
                    var myAnnotation = new mapkit.MarkerAnnotation(new mapkit.Coordinate(latitude, longitude), { 
                        color: "#9b6bcc", 
                        title: title,
                        subtitle: address
                    });
                    map.addAnnotation(myAnnotation);
                    // Hide the results box
                    $('#results').hide();
                });
            });
        } else {
            $('#results').hide();
        }
    });
</script>

推荐阅读