zoukankan      html  css  js  c++  java
  • GPS转换为百度坐标

    原文地址:http://www.cnblogs.com/zhaohuionly/archive/2013/06/18/3142623.html

    最近在做一个关于手机定位的小应用,需求是这样的,用户通过手机(Wp8)进行二维码扫描操作并且记录用户的当前位置,在PC上可以查看用户所在地图的位置,做法就是在用户扫描条码时,通过手机GPS获取当前在地图上的位置(采用百度静态地图,根据坐标直接生成图片)并将图片保存到数据库,PC端直接从数据库中读取并展示图片。问题是:生成的图片所呈现的位置与实际位置偏差太大。于是我开始踏上了寻找解决办法的道路。

      首先我检测我的硬件设备是否定位准确,我用WP8手机内置的地图进行了当前位置定位,结果没有问题,说明我的手机没有问题。

      由于用的是百度静态地图,我再次来到 百度地图API > 常见问题 下看到这么一条关于 坐标体系:

      4.1 坐标体系是否遵循国家对地理信息保密要求?

      百度对外接口的坐标系,都是经过国家测绘局加密处理,符合国家测绘局对地理信息保密要求。

      4.2 百度采用何种坐标体系?

      百度地图api中采用两种坐标体系,经纬度坐标系和墨卡托投影坐标系。前者单位是度,后者单位是米,具体定义可以参见百科词条解释:   

      http://baike.baidu.com/view/61394.htmhttp://baike.baidu.com/view/301981.htm

      4.3 百度坐标为何有偏移?

      国际经纬度坐标标准为WGS-84,国内必须至少使用国测局制定的GCJ-02,对地理位置进行首次加密。百度坐标在此基础上,进行了BD-09二次加密措施,更加保护了个人隐私。百度对外接口的坐标系并不是GPS采集的真实经纬度,需要通过坐标转换接口进行转换。      

      4.4 如何从其他体系的坐标迁移到百度坐标?

      坐标转换接口非公开。请将您的公司名称、项目名称、项目简介、联系人和联系方式,发邮件至mapapi@baidu.com咨询。有专人为您解答。

      也就是说由于受到国家一些法律法规限制,所有的电子地图服务提供商都需要给地图数据加上偏移和加密,所谓的地图数据加密偏移,其实就是用一个偏移算法对地图的经纬度做一个加减偏移量,从而达到与实际地图不一致。这个偏移算法本身是没有什么规律可言的,每家地图服务商都有一套自己的加密偏移算法,既然算法上没有什么规律可言,但是对于算法中生成的偏移量是否有规律呢?这个是可以肯定的,但是偏移算法中生成的偏移量是有规律而言的。偏移量的规律很难得到,要是能拿到这个偏移量,就可以说是破解了某一个地图服务商的地图加密。
      所以百度对外提供的坐标系是百度自己的坐标系,而手机GPS获得的是原始坐标,两者不在一个坐标系上,所以有很大的误差,我测试了一下,误差在千米之外。所以必须得把两者换成统一坐标系。换成原始GPS坐标在国内原则上是违法的,所以只能统一成各个地图运营商自己的坐标系,比如百度坐标系或者google坐标系。

      如何转换成百度坐标系:官方文档给的是:坐标转换接口非公开。于是我开始搜搜“GPS坐标转换为百度坐标”结果不负有心人呐终于找到了解决方案,特来此贴出来我整理的代码。

      百度地图坐标转换接口如下:  

      BMap.Convertor.translate(gpsPoint,0,translateCallback);     //真实经纬度转成百度坐标

      其中gpsPoint var gpsPoint = new BMap.Point(经度,纬度); ( GPS坐标)    0:代表GPS,也可以是2:google坐标    translateCallback:回掉函数

         下面是完整的测试GPS坐标转换百度坐标JS源码:

    复制代码
    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <style type="text/css">
    body, html,#allmap { 100%;height: 100%;overflow: hidden;margin:0;}
    #l-map{height:100%;78%;float:left;border-right:2px solid #bcbcbc;}
    #r-result{height:100%;20%;float:left;}
    </style>
    <script type="text/javascript" src="http://api.map.baidu.com/api?v=1.5&ak=9fb983ecd9b505f8fedcc9ab07c65e3e"></script>
    <script type="text/javascript" src="http://developer.baidu.com/map/jsdemo/demo/convertor.js"></script>
    <title>GPS转百度</title>
    </head>
    <body>
    <div id="allmap"></div>
    </body>
    </html>
    <script type="text/javascript">
    //GPS坐标
    var xx = 117.126575995835;
    var yy = 36.6702207308909;
    var gpsPoint = new BMap.Point(xx,yy);
    
    //地图初始化
    var bm = new BMap.Map("allmap");
    bm.centerAndZoom(gpsPoint, 15);
    bm.addControl(new BMap.NavigationControl());
    
    //添加谷歌marker和label
    var markergps = new BMap.Marker(gpsPoint);
    bm.addOverlay(markergps); //添加GPS标注
    var labelgps = new BMap.Label("我是GPS标注哦",{offset:new BMap.Size(20,-10)});
    markergps.setLabel(labelgps); //添加GPS标注
    
    //坐标转换完之后的回调函数
    translateCallback = function (point){
        var marker = new BMap.Marker(point);
        bm.addOverlay(marker);
        var label = new BMap.Label("我是百度标注哦",{offset:new BMap.Size(20,-10)});
        marker.setLabel(label); //添加百度label
        bm.setCenter(point);
        alert("转化为百度坐标为:"+point.lng + "," + point.lat);
    }
    
    setTimeout(function(){
        BMap.Convertor.translate(gpsPoint,0,translateCallback);     //真实经纬度转成百度坐标
    }, 2000);
    </script>
    复制代码

     本人用C#开发的WP8应用上面JS版的不适合  于是接着查找……

    找到百度的API转换方法为:

        http://api.map.baidu.com/ag/coord/convert?from=0&to=4&x=longitude&y=latitude

        其中:
        from: 来源坐标系   (0表示原始GPS坐标,2表示Google坐标)
          to: 转换后的坐标   (4就是百度自己啦,好像这个必须是4才行)
            x: 经度
                y: 纬度
                返回的结果是一个json字符串:
               {"error":0,"x":"MTIxLjUwMDIyODIxNDk2","y":"MzEuMjM1ODUwMjYwMTE3"}

                其中:
                error:是结果是否出错标志位,"0"表示OK
                x: 百度坐标系的经度(Base64加密)
                y: 百度坐标系的纬度(Base64加密)

    在WP8中测试源码都已加注释,不再一一解释,直接上源码

    前台XAML页面:

    复制代码
    <phone:PhoneApplicationPage
        x:Class="Crystal.Phone.App.Page.BaiduMapConvert"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
        xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        FontFamily="{StaticResource PhoneFontFamilyNormal}"
        FontSize="{StaticResource PhoneFontSizeNormal}"
        Foreground="{StaticResource PhoneForegroundBrush}"
        SupportedOrientations="Portrait" Orientation="Portrait"
        mc:Ignorable="d"
        shell:SystemTray.IsVisible="True">
    
        <!--LayoutRoot 是包含所有页面内容的根网格-->
        <Grid x:Name="LayoutRoot" Background="Transparent">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>
    
            <!--TitlePanel 包含应用程序的名称和页标题-->
            <StackPanel Grid.Row="0" Margin="12,17,0,28">
                <TextBlock Text="我的应用程序" Style="{StaticResource PhoneTextNormalStyle}"/>
                <TextBlock Text="百度地图" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
            </StackPanel>
    
            <!--ContentPanel - 在此处放置其他内容-->
            <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
                <Grid.RowDefinitions>
                    <RowDefinition Height="100" />
                    <RowDefinition />
                </Grid.RowDefinitions>
                <Button Name="btnConvert" Click="btnConvert_Click_1" Content="我的位置" HorizontalAlignment="Center"  VerticalAlignment="Center" />
                <Image x:Name="imgLocation" Stretch="Fill" Grid.Row="1"></Image>
            </Grid>
        </Grid>
    
    </phone:PhoneApplicationPage>
    复制代码

    后台XAML.cs

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Navigation;
    using Microsoft.Phone.Controls;
    using Microsoft.Phone.Shell;
    using System.IO;
    using Newtonsoft.Json;
    using Windows.Devices.Geolocation;
    using System.Text;
    using System.Windows.Media.Imaging;
    
    namespace Crystal.Phone.App.Page
    {
        public partial class BaiduMapConvert : PhoneApplicationPage
        {
            public BaiduMapConvert()
            {
                InitializeComponent();
            }
    
            private async void btnConvert_Click_1(object sender, RoutedEventArgs e)
            {
                Geolocator geo = new Geolocator();
                //判断是否开启了GPS定位
                if (geo.LocationStatus == PositionStatus.Disabled)
                {
                    MessageBox.Show("尚未开启位置服务!");
                    return;
                }
                Geoposition pos = await geo.GetGeopositionAsync();
    
                //获取当前纬度
                string Latitude = pos.Coordinate.Latitude.ToString();
    
                //获取当前经度
                string Longitude = pos.Coordinate.Longitude.ToString(); 
    
                //百度坐标转换API
                string path = "http://api.map.baidu.com/ag/coord/convert?from=0&to=4&x=" + Longitude + "&y=" + Latitude + "";
    
                //WebClient请求
                WebClient client = new WebClient();
                string strResult = await client.UploadStringTaskAsync(path,"");
                MapConvert mapConvert = new MapConvert();
                mapConvert=JsonConvert.DeserializeObject<MapConvert>(strResult);
                string lon = mapConvert.x;
                string lat = mapConvert.y;
    
                //进行Base64解码
                byte[] xBuffer = Convert.FromBase64String(lon);
                string  strX = Encoding.UTF8.GetString(xBuffer,0,xBuffer.Length);
    
                byte[] yBuffer = Convert.FromBase64String(lat);
                string  strY = Encoding.UTF8.GetString(yBuffer,0,xBuffer.Length);
    
                //生成静态图片
                string imgSrc = string.Format("http://api.map.baidu.com/staticimage?center={0},{1}&width=300&height=300&zoom=16&markers={2},{3}&markerStyles=l,A", strX, strY, strX, strY);
                
                //显示图片
                BitmapImage bitmapImage = new BitmapImage(new Uri(imgSrc, UriKind.Absolute));
                imgLocation.Source = bitmapImage;
            }
        }
    
        public class MapConvert
        {
            public string error { get; set; }
            public string x { get; set; }
            public string y { get; set; }
        }
    }
    复制代码

     以上就是我今天整理的关于GPS坐标转换为百度坐标的方法。

  • 相关阅读:
    volcanol的工控博客
    volcanol的工控博客
    volcanol的工控博客
    volcanol的工控博客
    volcanol的工控博客
    volcanol的工控博客
    volcanol的工控博客
    volcanol的工控博客
    volcanol的工控博客
    volcanol的工控博客
  • 原文地址:https://www.cnblogs.com/vvonline/p/4414352.html
Copyright © 2011-2022 走看看