昨日公司要求做一个静态百度地图图片生成到本地的功能,以前没做过,这次小小总结一下
百度地图API自己看(http://developer.baidu.com/map/index.php?title=static)
当然首先得调用百度地图API,无非就是前台后台,,我是用JS写的,(http://www.cnblogs.com/kulong995/p/3368048.html)这个人写的不错,是用c#写的调用百度地图,写的很不错,可以看看
百度地图是由一堆乱七八糟的数据拼接出来的路径,然而保存图片就需要用这个路径,所以首先要拿到这个路径
在调用百度API时候,首先要有百度给你的路径调用才行
比如
不多说,直接上代码,
<body onload="initMap()"> 地址:<input type="text" name="address" id="address" value="北京市" /> <button id="mapsearch">搜索</button> <input type="button" id="uploadMap" value="导出地图" onclick="saveImg()" /> <div style="width: 540px; height: 320px; border: 1px solid gray" id="container"></div> <p> <iframe id="testiframe" src="#" height="1" width="1"></iframe> <script type="text/javascript"> var map = new BMap.Map("container"); // 创建地图实例 var point = new BMap.Point(116.313127, 39.984242); // 创建点坐标 map.centerAndZoom(point, 13); map.addControl(new BMap.NavigationControl()); map.addControl(new BMap.ScaleControl()); map.addControl(new BMap.OverviewMapControl()); var marker = new BMap.Marker(point); // 创建标注 map.addOverlay(marker); // 将标注添加到地图中 marker.enableDragging();//可以拖拽 var staticWith = 540; var staticHeight = 220; function initMap() { var mapsearch = document.getElementById("mapsearch"); mapsearch.onclick = function () { var address = document.getElementById("address").value; if (address == "undefined" || address == "") { alert("请输入地址,再进行搜索!"); return; } var myGeo = new BMap.Geocoder(); myGeo.getPoint(address, function (point) { if (point) { marker.setPosition(point);//重新设置标注的坐标 window.setTimeout(function () {//移动地图 map.panTo(point); }, 2000); } }, "上海市"); } //生成图片 var mapsearch = document.getElementById("uploadMap"); mapsearch.onclick = function () { testStaticMap(); } function getStaticMap() { if (map == '' || map == 'undefined' || marker == '') { return; } var center = map.getCenter().lng + ',' + map.getCenter().lat; var markers = marker.getPosition().lng + ',' + marker.getPosition().lat; var zoom = map.getZoom(); var staticmapstr = 'http://api.map.baidu.com/staticimage?center=' + center + '&markers=' + markers + '&zoom=' + zoom + '&width=' + staticWith + '&height=' + staticHeight; //alert(staticmapstr);//生成的图片地址 return staticmapstr; } function testStaticMap() { var testiframe = document.getElementById("testiframe"); if (testiframe == "undefined" || testiframe == null || testiframe.src == "undefined") { return; } testiframe.src = getStaticMap(); testiframe.width = staticWith; testiframe.height = staticHeight; testiframe.document.execCommand("SaveAs"); alert(testiframe); //http://api.map.baidu.com/staticimage?center=116.313127,39.984242&markers=116.313127,39.984242&zoom=13&width=540&height=220 //DownLoadReportIMG(getStaticMap()); } } </script> </body>
功能没有完全实现,凑合着看吧,这个时候是已经拿到图片URL了,,只要用AJAX吧URL传到一般处理程序.ashx中,c#保存即可,,
C#保存图片代码段:
using (WebClient wc = new WebClient())
{
wc.DownloadFile(url(图片路径), saveFile(保存文件夹路径));
}
大工告成!!!