使用react-to-print打印@react-google-maps/api地图时标记(Marker)在预览中不显示的问题求助
使用react-to-print打印@react-google-maps/api地图时标记(Marker)在预览中不显示的问题求助
大家好,我现在遇到一个头疼的问题:我想实现打印带有Marker标记的Google地图,但在打印预览里只有地图本身能显示,Marker完全看不到。我明明是等Marker的onLoad函数执行完才打开预览的,一开始我以为是自定义图标的问题,但换成标准Marker也一样不显示。我用的是react-to-print库来处理打印,地图部分用的是@react-google-maps/api的GoogleMap、Marker和useJsApiLoader。有没有办法让自定义Marker在打印时正常显示出来呢?
我的组件代码如下:
import { useState, useEffect, useRef, useMemo } from 'react'; import { GoogleMap, Marker, useJsApiLoader } from '@react-google-maps/api'; // 项目中已定义的相关常量 const defaultZoom = 15; const containerStyle = { width: '100%', height: '400px' }; const MARKER_PATHS = { /* 自定义标记的路径配置 */ }; type PrintableLocationMapProps = { siteCoordinates: { lat: number; lng: number }; setLoadedMapsCount: (prev: number) => number; locationMarker?: { markerType: string; rotation: number; latitude: number; longitude: number; }; }; export default function PrintableLocationMap({ siteCoordinates, setLoadedMapsCount, locationMarker, }: PrintableLocationMapProps) { const { isLoaded } = useJsApiLoader({ googleMapsApiKey: process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY!, }); const [mapCenter, setMapCenter] = useState(siteCoordinates); const hasLoaded = useRef(false); useEffect(() => { setMapCenter(siteCoordinates); }, [siteCoordinates]); const markerIcon = useMemo(() => { if (!isLoaded || !locationMarker) return undefined; return { url: MARKER_PATHS[locationMarker.markerType], scaledSize: new window.google.maps.Size(32, 32), anchor: new window.google.maps.Point(16, 16), rotation: locationMarker.rotation, }; }, [isLoaded, locationMarker]); const handleMapLoad = () => { if (!hasLoaded.current) { hasLoaded.current = true; setLoadedMapsCount((prev) => prev + 1); } }; if (!isLoaded) return <p>Loading map…</p>; return ( <div className="printable-map border rounded-md shadow p-2"> <GoogleMap mapContainerStyle={containerStyle} center={mapCenter} zoom={defaultZoom} // 曾尝试用onTilesLoaded替代Marker的onLoad,问题依然存在 options={{ disableDefaultUI: true, gestureHandling: "none", zoomControl: false, draggable: false, }} > <Marker position={{ lat: mapCenter.lat, lng: mapCenter.lng }} onLoad={handleMapLoad} /> {locationMarker && ( <Marker position={{ lat: locationMarker.latitude, lng: locationMarker.longitude, }} icon={markerIcon} /> )} </GoogleMap> </div> ); }
我尝试过把地图加载完成的回调从Marker的onLoad换成GoogleMap的onTilesLoaded,但Marker还是不会在打印预览里显示。有没有朋友遇到过类似的情况,或者知道怎么解决这个Marker打印不显示的问题?
内容来源于stack exchange
相关产品推荐
相关产品推荐

