Home >Web Front-end >JS Tutorial >How to use JS and Amap to implement location area search function
How to use JS and Amap to implement location area retrieval function
With the popularity of mobile phones and the Internet, map navigation has become indispensable in our daily lives tool. The location area search function is also very common in map applications. For example, we can find nearby restaurants, movie theaters, gas stations, etc. through the search function.
This article will introduce how to use JS and Amap API to implement the location area retrieval function, and provide specific code examples.
<script src="https://webapi.amap.com/maps?v=1.4.15&key=your-key"></script>
Among them, your-key
needs to be replaced with your own developer Key.
<div id="mapContainer"></div>
var map = new AMap.Map("mapContainer", { resizeEnable: true, zoom: 13 });
Among them, mapContainer
is the id of the map container, and zoom
specifies the initial zoom level of the map.
In the HTML document, the sample code for adding the search box and search button is as follows:
<input type="text" id="keywordInput" /> <button onclick="search()">搜索</button>
In the JS code, the sample code for adding the search function is as follows:
function search() { var keyword = document.getElementById("keywordInput").value; AMap.service(["AMap.PlaceSearch"], function() { var placeSearch = new AMap.PlaceSearch({ map: map }); placeSearch.search(keyword); }); }
Among them, the AMap.service
method will asynchronously load (lazy loading) the required AMAP service, so you need to create a location search object in the callback function of this method and call search
Method to search.
In the JS code, the sample code for adding an event listener is as follows:
map.on("complete", function() { // 当地图加载完成时,触发该事件 // 在这里可以对搜索结果进行一些额外的处理 // 比如在地图上添加标记点、显示附近的位置等等 });
Through the above steps, we have realized the use of JS and Amap API to achieve location area retrieval. Function. Hope this article can be helpful to you.
References:
The above is the detailed content of How to use JS and Amap to implement location area search function. For more information, please follow other related articles on the PHP Chinese website!