Using Google Maps and Baidu Maps in same app

后端 未结 6 969
一生所求
一生所求 2020-12-31 22:02

I\'m wondering if there are anyone out that have implemented Google Maps V2 and Baidu Maps in the same version; because GM doesn\'t work as intended in China?

Or sho

6条回答
  •  北海茫月
    2020-12-31 22:06

    You can use both Google Maps and Baidu Maps side by side, but make sure to convert from the WGS-84 coordinates (used by most of the world) to Baidu's coordinates (BD-09, different from China's GCJ-02). Here's some code that does that, based on an example from the Baidu Maps API:

    // Google coordinates
    var gPoint = new BMap.Point(121.4914, 31.2423);  // lon, lat of the Bund Museum in Shanghai - https://www.google.com/maps/@31.2423,121.4914,19z
    // gPoint = new BMap.Point(-122.0851053, 37.4219593);  // lon, lat of the Googleplex (no Baidu map data but zooms out in Mountain View)
    
    var labelOffset = { offset: new BMap.Size(20, -10) };
    
    // Initialize map
    var map = new BMap.Map('allmap');
    map.centerAndZoom(gPoint, 15);
    map.addControl(new BMap.ScaleControl({anchor: BMAP_ANCHOR_TOP_LEFT}));  // add scale
    map.addControl(new BMap.NavigationControl());
    map.addControl(new BMap.MapTypeControl());   // map type control: street/satellite/2.5D
    map.enableScrollWheelZoom();  // mouse wheel scroll is disabled by default
    
    // Add Google marker and label
    var markerG = new BMap.Marker(gPoint);
    map.addOverlay(markerG);
    markerG.setLabel(new BMap.Label('Google coordinates marker appears
    at incorrect location on Baidu Map', labelOffset)); // Coordinate conversion ... GCJ-02 coordinates ... Baidu coordinates BMap.Convertor.translate(gPoint, 2, function (point) { var marker = new BMap.Marker(point); map.addOverlay(marker); marker.setLabel(new BMap.Label('Converted to Baidu coordinates:
    ' + point.lng + ', ' + point.lat + '
    (note the offset of ' + (map.getDistance(gPoint, point)).toFixed(2) + ' meters)', labelOffset)); map.addOverlay(new BMap.Polyline([gPoint, point])); // draw a line between points });
    
    
    
    
    

    If the snippet above doesn't work due to the way StackOverflow sandboxes scripts, try the JSbin demo of Google -> Baidu coordinates conversion instead.

    If you must perform the conversion offline, check out the evil transform project on GitHub.

    It's unclear though what coordinate types browsers localized in Chinese will return via the navigator.geolocation API. I've made a test app for that and posted the question at
    Showing navigator.geolocation.getCurrentPosition in Baidu Maps.

    Further reading:

    • What causes the GPS shift in China?
    • Restrictions on geographic data in China

提交回复
热议问题