js实现街景图
使用 Google Maps JavaScript API 实现街景
在HTML文件中引入Google Maps API脚本,替换YOUR_API_KEY为实际API密钥:
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&libraries=streetView" async defer></script>
创建街景容器并初始化:
<div id="street-view" style="width: 100%; height: 500px;"></div>
<script>
function initMap() {
const fenway = { lat: 42.345573, lng: -71.098326 };
const panorama = new google.maps.StreetViewPanorama(
document.getElementById("street-view"),
{
position: fenway,
pov: { heading: 34, pitch: 10 },
}
);
}
</script>
通过Three.js自定义街景实现
安装Three.js库:
npm install three
创建全景查看器基础代码:
import * as THREE from 'three';
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const geometry = new THREE.SphereGeometry(500, 60, 40);
geometry.scale(-1, 1, 1);
const texture = new THREE.TextureLoader().load('panorama.jpg');
const material = new THREE.MeshBasicMaterial({ map: texture });
const sphere = new THREE.Mesh(geometry, material);
scene.add(sphere);
camera.position.set(0, 0, 0.1);
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
街景控制参数配置
Google街景常用控制参数:
const panoramaOptions = {
position: {lat: 40.756, lng: -73.986}, // 坐标位置
pov: {
heading: 270, // 0-360度水平视角
pitch: 0, // -90到90度垂直视角
zoom: 1 // 缩放级别
},
addressControl: true,
showRoadLabels: true,
zoomControl: true,
linksControl: true
};
街景导航功能实现
添加街景导航控制按钮:
document.getElementById('rotate-left').addEventListener('click', () => {
panorama.setPov({
heading: (panorama.getPov().heading - 30) % 360,
pitch: panorama.getPov().pitch
});
});
document.getElementById('zoom-in').addEventListener('click', () => {
panorama.setZoom(panorama.getZoom() + 1);
});
移动端适配处理
添加触摸事件支持:
const touchHandler = new Hammer(document.getElementById('street-view'));
touchHandler.get('pan').set({ direction: Hammer.DIRECTION_ALL });
touchHandler.on('pan', (ev) => {
panorama.setPov({
heading: panorama.getPov().heading - ev.deltaX * 0.2,
pitch: Math.max(-90, Math.min(90, panorama.getPov().pitch + ev.deltaY * 0.1))
});
});
性能优化建议
使用低分辨率预览模式:

const lowResPanorama = new google.maps.StreetViewPanorama(
container,
{
position: location,
visible: true,
enableCloseButton: false,
showRoadLabels: false,
zoomControlOptions: {
position: google.maps.ControlPosition.LEFT_BOTTOM
},
linksControl: false
}
);






