<!-- hybrid/html/map.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>高德地图</title>
<!-- <script src="https://webapi.amap.com/loader.js"></script> -->
<script src="https://cdn.bootcss.com/vue/2.6.11/vue.js"></script>
<style>
#map-container {
width: 100%;
height: 584px;
border-radius: 22px;
z-index: 4;
}
/* 新增:隐藏高德默认标记图标 */
#map-container .amap-marker img[src*="mark_bs.png"] {
display: none !important;
}
</style>
</head>
<body>
<div id="map-container"></div>
<script type="text/javascript" src="./js/uni.webview.0.1.52.js">
</script>
<script>
window._AMapSecurityConfig = {
securityJsCode: 'cf331d54f67e306ca5c0b17f7122d559'
};
</script>
<script src="https://webapi.amap.com/maps?v=2.0&key=f3323c24769b10828db07f07c0fcec0d&plugin=AMap.MarkerCluster">
</script>
<script src="https://webapi.amap.com/ui/1.1/main.js"></script>
<script>
// 确保UniApp通信桥接准备就绪
function setupUniBridge() {
return new Promise(resolve => {
if (typeof uni.postMessage === 'function') {
return resolve();
}
document.addEventListener('UniAppJSBridgeReady', resolve);
});
}
// 向UniApp发送消息(兼容H5和App环境)
async function sendMessageToUniApp(data) {
// 1. 确保桥接就绪(仅对App环境有效,H5环境会直接resolve)
await setupUniBridge();
// 2. 区分环境发送消息
if (isH5Environment()) {
// H5环境:使用浏览器原生postMessage
console.log('H5环境,使用window.parent.postMessage发送消息');
window.parent.postMessage({
type: 'webviewMessage', // 自定义类型,方便UniApp识别
data: JSON.stringify(data)
}, '*'); // 第三个参数为目标域名,*表示允许所有(开发环境可用,生产环境需指定具体域名)
} else if (window.uni && typeof uni.postMessage === 'function') {
// App环境:使用uni.postMessage
console.log('App环境,使用uni.postMessage发送消息');
uni.postMessage({
data: JSON.stringify(data)
});
} else {
console.error('未支持的环境,无法发送消息');
}
}
// 辅助函数:判断是否为H5环境(浏览器环境)
function isH5Environment() {
const protocol = window.location.protocol;
// H5环境的协议通常是http:或https:
return protocol === 'http:' || protocol === 'https:';
}
// 解析URL参数
const params = new URLSearchParams(location.search);
const points = JSON.parse(params.get('points') || '[]');
const markers = JSON.parse(params.get('markers') || '[]');
// 初始化地图
const map = new AMap.Map('map-container', {
zoom: 10,
center: [points[0].lng, points[0].lat],
showBuildingBlock: true
});
// 自定义单个标记内容(保持原有样式,修复图片路径)
function createMarkerContent(markerData) {
// 优先使用本地图片,失败则用备用图(确保是自定义图标)
const imageUrl = './img/flag.png';
return `
<div style="position:relative;z-index:1000;">
<img src="${imageUrl}" style="width:30px; height:30px;"
alt="${markerData.title}">
<div style="position:absolute; bottom:-20px; left:50%; transform: translateX(-50%);
background: #f5e7e7; padding:3px 8px;
border-radius: 18px; white-space:nowrap;
font-family:ShuHuiTi, sans-serif; font-size: 12px; font-weight: bold;
border: 2px solid #F47C58; color:#E4393C;">
${markerData.title}
</div>
</div>
`;
}
// 聚合点渲染函数
function _renderClusterMarker(context) {
const count = context.count;
console.log('渲染聚合点,数量:', count);
// 通过JS直接设置样式(优先级更高)
const div = document.createElement('div');
div.innerHTML = count;
// 强制设置关键样式(覆盖默认)
div.style.width = '40px';
div.style.height = '40px';
div.style.backgroundColor = '#FF9A44';
div.style.borderRadius = '50%';
div.style.display = 'flex';
div.style.alignItems = 'center';
div.style.justifyContent = 'center';
div.style.color = 'white';
div.style.fontWeight = 'bold';
// 设置聚合点偏移(确保居中)
context.marker.setOffset(new AMap.Pixel(-20, -20));
context.marker.setContent(div); // 通过context.marker设置内容
}
// 单个标记渲染函数
function _renderMarker(context) {
const markerData = context.data[0].originalData;
// 1. 生成标记内容
const content = createMarkerContent(markerData);
// 2. 设置标记内容
context.marker.setContent(content);
// 3. 校准偏移量(根据内容尺寸计算,确保标记中心与经纬度对齐)
// 内容总高度:图片30px + 标题区域20px = 50px,向上偏移50px使底部对齐定位点
context.marker.setOffset(new AMap.Pixel(-15, -50)); // 水平偏移:30px宽/2=15px
// 4. 绑定点击事件
context.marker.on('click', async () => {
const message = {
type: 'markerClick',
data: markerData
};
console.log('H5发送消息:', message);
// 优先使用uni.postMessag
await sendMessageToUniApp({
type: 'markerClick',
data: markerData
});
});
}
// 绘制路线(保持原有功能)
function drawRouteAndPoints() {
if (points.length === 0) return;
const path = points.map(p => [p.lng, p.lat]);
new AMap.Polyline({
path: path,
strokeColor: "#32CD32",
strokeWeight: 5,
zIndex: 500,
map: map
});
if (points.length >= 2) {
AMap.plugin('AMap.Driving', () => {
const driving = new AMap.Driving({
map: map,
policy: AMap.DrivingPolicy.LEAST_TIME,
zIndex: 550
});
driving.search(
[points[0].lng, points[0].lat],
[points[points.length - 1].lng, points[points.length - 1].lat]
);
});
}
}
// 初始化聚合标记
function initClusterMarkers() {
if (!markers.length) return;
// 转换数据格式为官方示例要求的结构(包含lnglat字段)
const clusterPoints = markers.map(marker => ({
lnglat: new AMap.LngLat(marker.lng, marker.lat), // 官方要求的经纬度格式
originalData: marker // 保留原始数据供渲染使用
}));
// 参考官方示例:插件加载后初始化聚合
AMap.plugin('AMap.MarkerCluster', function() {
if (typeof AMap.MarkerCluster === 'undefined') {
console.error('聚合插件加载失败');
return;
}
// 配置聚合参数
const cluster = new AMap.MarkerCluster(map, clusterPoints, {
gridSize: 80, // 网格大小(官方示例默认60,可调整)
maxZoom: 15, // 最大聚合级别
minClusterSize: 2, // 最小聚合数量(测试时可改为1)
zoomOnClick: true,
averageCenter: true,
zIndex: 2000,
// 聚合点参数名
renderClusterMarker: _renderClusterMarker,
// 单个标记参数名
renderMarker: _renderMarker
});
// 调整视野
const bounds = new AMap.Bounds();
clusterPoints.forEach(point => bounds.extend(point.lnglat));
map.setBounds(bounds, [50, 50, 50, 50]);
});
}
// 地图加载完成后初始化
map.on('complete', function() {
console.log('地图加载完成,初始化组件');
initClusterMarkers();
if (points.length > 0) drawRouteAndPoints();
});
map.on('error', (err) => console.error('地图错误:', err));
// 构建带标题的HTML内容
// markers.forEach(marker => {
// // 构建HTML内容(包含图片和标题)
// const content = `
// <div style="background: linear-gradient(180deg, #E3383B 0%, #F47C58 98%); padding:6px; border-radius: 8px;">
// <div style=" white-space:wrap;
// font-family:AlibabaPuHuiTi-SemiBold; font-size: 15px;
// margin-top:5px;color:#fff;width:100%;">闽宁新貌展示中心</div>
// <div style=" white-space:wrap;text-indent: 1em;letter-spacing: 1px;
// font-family:AlibabaPuHuiTi-RegularL3; font-size: 10px;
// margin-top:5px;color:#fff;width:100%;">
// 闽宁新貌展示中心,生动呈现闽宁协作丰硕成果,见证昔日“干沙滩”蜕变为今日“金沙滩”的壮丽历程。 </div>
// <img src="./img/ditu.png" style="width:200px; height:110px; display:block;margin-top:5px;">
// </div>
// `;
// const markerObj = new AMap.Marker({
// position: [marker.lng, marker.lat],
// content: content, // 使用HTML内容
// anchor: 'bottom-center', // 锚点在底部中心
// offset: new AMap.Pixel(0, -25) // 向上偏移
// });
// markerObj.on('click', () => {
// console.log('window--uni', uni, window);
// // console.log(marker, '000');
// // 将数据转为字符串
// const message = JSON.stringify({
// type: 'markerClick',
// title: marker.title
// });
// window.parent.postMessage(message, '*');
// // 通过uni.postMessage发送数据
// // uni.postMessage({
// // data: JSON.stringify(message) // 发送字符串
// // });
// });
// map.add(markerObj);
// });
// 2. 在map加载完成后初始化聚合点
// map.on('complete', function() {
// // 创建聚合实例
// const cluster = new AMap.MarkerClusterer(map, markers.map(m => {
// return new AMap.Marker({
// position: [m.lng, m.lat],
// content: createMarkerContent(m) // 自定义标记
// });
// }), {
// gridSize: 80,
// maxZoom: 18,
// renderClusterMarker: renderCluster
// });
// // // 转换数据格式
// // const clusterPoints = markers.map(marker => ({
// // lnglat: [marker.lng, marker.lat],
// // title: marker.title,
// // originalData: marker // 保留原始数据
// // }));
// // console.log('在map加载完成后初始化聚合点', clusterPoints);
// // // 确保有聚合点数据
// // if (clusterPoints.length === 0) return;
// // 使用MarkerCluster插件
// // AMap.plugin('AMap.MarkerCluster', function() {
// // console.log("聚合插件加载完成");
// // // 创建聚合点
// // const cluster = new AMap.MarkerCluster(map, clusterPoints, {
// // gridSize: 80, // 聚合网格像素大小
// // maxZoom: 18, // 最大聚合级别
// // minClusterSize: 2, // 最小聚合数量
// // zoomOnClick: true, // 点击聚合点是否放大地图
// // averageCenter: true, // 聚合点是否使用平均值中心
// // // 定义聚合点样式
// // renderClusterMarker: function(context) {
// // console.log('定义聚合点样式-context', context);
// // // const count = context.count;
// // // const div = document.createElement('div');
// // // div.innerHTML = `
// // // <div style="background: #FF9A44;
// // // border-radius: 50%;
// // // width: 40px;
// // // height: 40px;
// // // display: flex;
// // // align-items: center;
// // // justify-content: center;
// // // color: white;
// // // font-weight: bold;
// // // z-index:99;">
// // // ${count}
// // // </div>
// // // `;
// // const count = context.count;
// // const div = document.createElement('div');
// // div.style.background = '#FF9A44';
// // div.style.borderRadius = '50%';
// // div.style.width = '40px';
// // div.style.height = '40px';
// // div.style.display = 'flex';
// // div.style.alignItems = 'center';
// // div.style.justifyContent = 'center';
// // div.style.color = 'white';
// // div.style.fontWeight = 'bold';
// // div.style.zIndex = '99';
// // div.innerHTML = count;
// // // context.marker.setContent(div);
// // return div;
// // },
// // // 自定义标记点样式
// // renderMarker: function(context) {
// // const markerData = context.data[0].originalData;
// // // console.log('自定义标记点样式-context', context);
// // // const marker = new AMap.Marker({
// // // position: [markerData.lng, markerData.lat],
// // // content: `
// // // <div style="position:relative; text-align:center;z-index:100;">
// // // <img src="./img/flag.png"
// // // style="width:40px; height:50px; display:block;">
// // // <div style="position:absolute; bottom:-90%; left:0%; transform:translateX(-50%);
// // // background: rgba(227, 57, 59, 0.1); padding:6px 0;
// // // border-radius: 18px; white-space:wrap;
// // // font-family:ShuHuiTi; font-size: 12px;font-weight: bold;
// // // margin-top:5px;border: 2px solid #F47C58;color:#E4393C;width:80px;">
// // // ${markerData.title}
// // // </div>
// // // </div>
// // // `,
// // // offset: new AMap.Pixel(0, 0)
// // // });
// // // 创建自定义内容
// // const content = `
// // <div style="position:relative; text-align:center;z-index:100;">
// // <img src="./img/flag.png" style="width:40px; height:50px; display:block;">
// // <div style="position:absolute; bottom:-90%; left:50%; transform:translateX(-50%);
// // background: rgba(227, 57, 59, 0.1); padding:6px 0; font-family:ShuHuiTi; font-size: 12px;font-weight: bold;
// // margin-top:5px;border: 2px solid #F47C58;color:#E4393C;width:80px; border-radius: 18px;">
// // ${markerData.title} </div> </div> `;
// // const marker = new AMap.Marker({
// // position: [markerData.lng, markerData.lat],
// // content: content,
// // offset: new AMap.Pixel(-2, -4) // 根据实际图片调整偏移
// // });
// // // 绑定聚合点点击事件
// // // marker.on('click', async function(e) {
// // // console.log(e, 'bbbbb');
// // // sendMessageToUniApp({
// // // type: 'markerClick',
// // // center: e.lnglat
// // // });
// // // });
// // // // console.log('聚合点点', marker);
// // // map.add(marker);
// // // 绑定标记点击事件
// // marker.on('click', async function(e) {
// // 发送消息给UniApp
// // await sendMessageToUniApp({
// // type: 'markerClick',
// // data: markerData
// // });
// // });
// // return marker;
// // },
// // });
// // // 绑定聚合点点击事件
// // cluster.on('click', async function(e) {
// // console.log(e, 'bbbbb');
// // // 发送聚合点点击事件
// // await sendMessageToUniApp({
// // type: 'clusterClick',
// // data: {
// // count: e.clusterData.count,
// // center: e.clusterData.center,
// // markers: e.clusterData.markers
// // }
// // });
// // });
// // });
// });
// 2. 绘制路线
// const path = points.map(p => [p.lng, p.lat]);
// new AMap.Polyline({
// path: path,
// strokeColor: "#32CD32",
// strokeWeight: 5,
// map: map
// });
// 3. 添加起点终点标记
// points.forEach((point, i) => {
// new AMap.Marker({
// position: [point.lng, point.lat],
// // content: `<div class="point-label">${i === 0 ? '起' : '终'}</div>`,
// offset: new AMap.Pixel(-10, -10),
// map: map
// });
// });
// 4. 绘制驾车路径(如果需要,可以注释掉直线路径,保留驾车路径)
// 注意:这里同时绘制了直线和驾车路径,可能会重叠
// if (points.length >= 2) {
// AMap.plugin('AMap.Driving', () => {
// const driving = new AMap.Driving({
// map: map, // 这样驾车路线会直接显示在地图上
// policy: AMap.DrivingPolicy.LEAST_TIME
// });
// driving.search(
// [points[0].lng, points[0].lat],
// [points[points.length - 1].lng, points[points.length - 1].lat],
// (status, result) => {
// // 可以根据结果处理
// }
// );
// });
// }
// 1. 绘制路线
// if (points.length > 0) {
// const path = points.map(p => [p.lng, p.lat]);
// new AMap.Polyline({
// path: path,
// strokeColor: "#32CD32",
// strokeWeight: 5,
// map: map
// });
// // 添加起点终点标记
// points.forEach((point, i) => {
// new AMap.Marker({
// position: [point.lng, point.lat],
// offset: new AMap.Pixel(-10, -10),
// map: map
// });
// });
// // 绘制驾车路径(如果需要)
// if (points.length >= 2) {
// AMap.plugin('AMap.Driving', () => {
// const driving = new AMap.Driving({
// map: map,
// policy: AMap.DrivingPolicy.LEAST_TIME
// });
// driving.search(
// [points[0].lng, points[0].lat],
// [points[points.length - 1].lng, points[points.length - 1].lat]
// );
// });
// }
// }
</script>
</body>
</html>点击点标记只有console.log('H5发送消息:', message);这个打印,其他的没有反应
最新发布