解决:腾讯地图API跨域问题,地图选点,搜索

2024-04-27 18:32

本文主要是介绍解决:腾讯地图API跨域问题,地图选点,搜索,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

用jsonp,解决跨域,请求url后面要加上 output=jsonp,直接复制代码,换上自己的key可用,先上效果图

$.ajax({type: 'get',url: 'https://apis.map.qq.com/ws/place/v1/suggestion?output=jsonp',async: false,data: params,dataType: 'jsonp',headers: {'Access-Control-Allow-Origin': '*','Access-Control-Allow-Methods': 'GET,POST',},success: function (result) {reslove(result)},error: function (xhr, errorType, error) {console.log('xhr', xhr)console.log('errorType', errorType)console.log('error', error)reject(xhr)},complete: function () { },})
<style>
* {margin: 0;padding: 0;
}#container {position: fixed;top: 50px;width: 100vw;bottom: 0;
}.search_part {position: fixed;top: 0;width: 100%;box-sizing: border-box;color: #fff;height: 50px;display: flex;align-items: center;padding: 0 20px;line-height: 50px;background: #ff8080;
}#place_list {position: fixed;top: 50px;width: 100vw;bottom: 0;z-index: 2;overflow-y: scroll;padding: 0 20px;box-sizing: border-box;background: #fff;display: none;
}#cancel_btn{display: none;
}.back {width: 20px;
}.search_wrap {flex: 1;position: relative;height: 30px;display: flex;align-items: center;line-height: 30px;margin: 0 20px;overflow: hidden;border-radius: 15px;background: rgba(0, 0, 0, 0.4);
}.search_wrap input {border: none;height: 100%;outline: none;flex: 1;color: #fff;margin-left: 10px;background: transparent;
}.icon_search {width: 18px;height: 18px;margin-left: 20px;
}.no_place {text-align: center;margin-top: 100px;color: #aaa;
}.placeItem{padding: 10px 0;border-bottom: 1px solid #eee;
}.place_title{color: #333;font-size: 14px;
}
.sub_place{color: #aaa;margin-top: 10px;font-size: 12px;
}
.no_more{font-size: 14px;padding: 20px 0;text-align: center;color: #aaa;
}.loader {position: fixed;top: 0;bottom: 0;left: 0;right: 0;display: flex;width: 100%;height: 100%;display: flex;justify-content: center;align-items: center;margin: 0 auto;z-index: 9;background: rgba(255, 255, 255, 0.6);/* Delay both the second and third circle at the start */}.loader .circle {background-color: #ff8080;margin-right: 4px;width: 10px;height: 10px;border-radius: 50%;animation: loadingcircle 1s infinite;animation-iteration-count: infinite;}.loader .circle:last-child {margin-right: 0px;}.loader .circle:nth-child(2) {animation-delay: 0.1s;}.loader .circle:nth-child(3) {animation-delay: 0.2s;}@keyframes loadingcircle {0% {transform: scale(1);}50% {transform: scale(0);}100% {transform: scale(1);}}</style>
<body><div class="search_part"><div class="search_wrap"><img class="icon_search" src="./static/search.png" alt="" /><input id="keyword" type="text" /></div><div id="search_btn">搜索</div><div id="cancel_btn">取消</div></div><div id="place_list"><div class="no_place"><img src="./static/no_address.png" alt="" /></div></div><!-- 定义地图显示容器 --><div id="container"></div>
</body>
<script src="https://map.qq.com/api/gljs?v=1.exp&key=腾讯地图key"></script>
<script src="./js/jquery-3.5.1.js"></script>
<script src="./js/lodash.js"></script>
<script>$(function () {let placeList = []let map = nulllet pager = {page_index: 1,page_size: 20}let keyword = ''//关键词let more = true// 地图初始化initMap()$('#keyword').focus(function () {$('#place_list').show()})$('#cancel_btn').click(function () {$('#place_list').hide()$(this).hide()$('#search_btn').show()})$('#search_btn').click(function () {$(this).hide()$('#cancel_btn').show()$('#keyword').focus()})$('#keyword').focus(function () {$('#cancel_btn').show()$('#search_btn').hide()})// 地址搜索$('#keyword').on('input propertychange',_.debounce(function () {keyword = $(this).val()if (keyword != '') {getSearchResult()}}, 500))// 触底加载$('#place_list').on('scroll', function (res) {let scrollHeight = $(this)[0].scrollHeightlet scrollTop = $(this).scrollTop()let height = $(this).height()if ((scrollTop + height >= scrollHeight) && more) {console.log('触底了')pager.page_index++getSearchResult()}})// 地点选择$(document).delegate('.placeItem', 'click', function () {let lat = $(this).attr('lat')let lng = $(this).attr('lng')console.log()$('#place_list').hide()map.panTo([Number(lat), Number(lng)])// map.setCenter(new TMap.LatLng(lat, lng))})function getSearchResult() {let data = {...pager, keyword}showLoading()placeSearch(data).then(res => {let html = ''let result = res.dataconsole.log(res.data)for (let index in result) {let item = result[index]html += `<div class="placeItem" lat="${item.location.lat}" lng="${item.location.lng}"><div class="place_title">${item.address}</div><div class="sub_place">${item.address}</div></div>`}if (result.length == 0 && data.page_index == 1) {more = falsehtml = `<div class="no_place"><img src="./static/no_address.png" alt="" /></div>`} else if ((data.page_index > 1 && data.page_size > result.length) || (data.page_index == 1 && data.page_size > result.length)) {// 加载完全部more = falsehtml += '<div class="no_more">没有更多啦~</div>'}if (data.page_index == 1) {placeList = result$('#place_list').html(html)} else {placeList.concat(result)$('#place_list').append(html)}$('.loader').remove()})}function placeSearch(data = {}) {return new Promise((reslove, reject) => {let params = {key: 'OLBBZ-APHKX-AQD4Y-TX3NS-SU6Q5-BHBTH',...data}$.ajax({type: 'get',url: 'https://apis.map.qq.com/ws/place/v1/suggestion?output=jsonp',async: false,data: params,dataType: 'jsonp',headers: {'Access-Control-Allow-Origin': '*','Access-Control-Allow-Methods': 'GET,POST',},success: function (result) {reslove(result)},error: function (xhr, errorType, error) {console.log('xhr', xhr)console.log('errorType', errorType)console.log('error', error)reject(xhr)},complete: function () { },})})}//地图初始化函数,本例取名为init,开发者可根据实际情况定义function initMap() {//定义地图中心点坐标var center = new TMap.LatLng(39.98412, 116.307484)//定义map变量,调用 TMap.Map() 构造函数创建地图map = new TMap.Map(document.getElementById('container'), {center: center, //设置地图中心点坐标zoom: 16, //设置地图缩放级别pitch: 0, //设置俯仰角rotation: 45, //设置地图旋转角度})var marker = marker = new TMap.MultiMarker({id: 'marker-layer',map: map,styles: {"marker": new TMap.MarkerStyle({"width": 35,"height": 35,"src": './static/location.png'})},geometries: [{"styleId": 'marker',"position": new TMap.LatLng(39.98412, 116.307484),"properties": {"title": "marker"}}]});map.on("click", function (evt) {let lat = evt.latLng.getLat().toFixed(6);let lng = evt.latLng.getLng().toFixed(6);if (marker) {marker.setMap(null);marker = null;}marker = new TMap.MultiMarker({id: 'marker-layer',map: map,styles: {"marker": new TMap.MarkerStyle({"width": 35,"height": 35,"src": './static/location.png'})},geometries: [{"styleId": 'marker',"position": new TMap.LatLng(lat, lng),"properties": {"title": "marker"}}]});map.panTo([lat, lng])})}})</script>```

这篇关于解决:腾讯地图API跨域问题,地图选点,搜索的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/941226

相关文章

线上Java OOM问题定位与解决方案超详细解析

《线上JavaOOM问题定位与解决方案超详细解析》OOM是JVM抛出的错误,表示内存分配失败,:本文主要介绍线上JavaOOM问题定位与解决方案的相关资料,文中通过代码介绍的非常详细,需要的朋... 目录一、OOM问题核心认知1.1 OOM定义与技术定位1.2 OOM常见类型及技术特征二、OOM问题定位工具

C++右移运算符的一个小坑及解决

《C++右移运算符的一个小坑及解决》文章指出右移运算符处理负数时左侧补1导致死循环,与除法行为不同,强调需注意补码机制以正确统计二进制1的个数... 目录我遇到了这么一个www.chinasem.cn函数由此可以看到也很好理解总结我遇到了这么一个函数template<typename T>unsigned

PHP应用中处理限流和API节流的最佳实践

《PHP应用中处理限流和API节流的最佳实践》限流和API节流对于确保Web应用程序的可靠性、安全性和可扩展性至关重要,本文将详细介绍PHP应用中处理限流和API节流的最佳实践,下面就来和小编一起学习... 目录限流的重要性在 php 中实施限流的最佳实践使用集中式存储进行状态管理(如 Redis)采用滑动

Vue3绑定props默认值问题

《Vue3绑定props默认值问题》使用Vue3的defineProps配合TypeScript的interface定义props类型,并通过withDefaults设置默认值,使组件能安全访问传入的... 目录前言步骤步骤1:使用 defineProps 定义 Props步骤2:设置默认值总结前言使用T

504 Gateway Timeout网关超时的根源及完美解决方法

《504GatewayTimeout网关超时的根源及完美解决方法》在日常开发和运维过程中,504GatewayTimeout错误是常见的网络问题之一,尤其是在使用反向代理(如Nginx)或... 目录引言为什么会出现 504 错误?1. 探索 504 Gateway Timeout 错误的根源 1.1 后端

Web服务器-Nginx-高并发问题

《Web服务器-Nginx-高并发问题》Nginx通过事件驱动、I/O多路复用和异步非阻塞技术高效处理高并发,结合动静分离和限流策略,提升性能与稳定性... 目录前言一、架构1. 原生多进程架构2. 事件驱动模型3. IO多路复用4. 异步非阻塞 I/O5. Nginx高并发配置实战二、动静分离1. 职责2

解决升级JDK报错:module java.base does not“opens java.lang.reflect“to unnamed module问题

《解决升级JDK报错:modulejava.basedoesnot“opensjava.lang.reflect“tounnamedmodule问题》SpringBoot启动错误源于Jav... 目录问题描述原因分析解决方案总结问题描述启动sprintboot时报以下错误原因分析编程异js常是由Ja

深度剖析SpringBoot日志性能提升的原因与解决

《深度剖析SpringBoot日志性能提升的原因与解决》日志记录本该是辅助工具,却为何成了性能瓶颈,SpringBoot如何用代码彻底破解日志导致的高延迟问题,感兴趣的小伙伴可以跟随小编一起学习一下... 目录前言第一章:日志性能陷阱的底层原理1.1 日志级别的“双刃剑”效应1.2 同步日志的“吞吐量杀手”

MySQL 表空却 ibd 文件过大的问题及解决方法

《MySQL表空却ibd文件过大的问题及解决方法》本文给大家介绍MySQL表空却ibd文件过大的问题及解决方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考... 目录一、问题背景:表空却 “吃满” 磁盘的怪事二、问题复现:一步步编程还原异常场景1. 准备测试源表与数据

解决Nginx启动报错Job for nginx.service failed because the control process exited with error code问题

《解决Nginx启动报错Jobfornginx.servicefailedbecausethecontrolprocessexitedwitherrorcode问题》Nginx启... 目录一、报错如下二、解决原因三、解决方式总结一、报错如下Job for nginx.service failed bec