如何不显示地图就获取位置数据?
使用“同步加载插件的方式”,引用各类插件,就可以不创建地图,直接获取地图数据。
以下用IP定位做为例子,详细讲述“如何不显示地图就获取当前位置”。
引入城市定位插件,更多插件与使用方法请见插件类总览
<script type="text/javascript" src="http://webapi.amap.com/maps?v=1.3&key=您的Key&plugin=AMap.CitySearch"></script>
实例化城市定位
var citysearch = new AMap.CitySearch();
定位结果,如果成功返回城市名称,如果失败返回错误信息
citysearch.getLocalCity(function(status, result) { if (status === 'complete' && result.info === 'OK') { if (result && result.city && result.bounds) { var cityinfo = result.city; var citybounds = result.bounds; document.getElementById('tip').innerHTML = '您当前所在城市:'+cityinfo; } } else { document.getElementById('tip').innerHTML = result.info; } });
截图
全部源代码
<!doctype html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width"> <title>根据ip定位</title> <script type="text/javascript" src="http://webapi.amap.com/maps?v=1.3&key=0250860ccb5953fa5d655e8acf40ebb7&plugin=AMap.CitySearch"></script> </head> <body> <div id="container"></div> <div class="button-group"> <input type="button" class="button" value="显示当前城市" onClick="javascript:showCityInfo()"/> </div> <div id="tip"></div> <script type="text/javascript"> //获取用户所在城市信息 function showCityInfo() { //实例化城市查询类 var citysearch = new AMap.CitySearch(); //自动获取用户IP,返回当前城市 citysearch.getLocalCity(function(status, result) { if (status === 'complete' && result.info === 'OK') { if (result && result.city && result.bounds) { var cityinfo = result.city; var citybounds = result.bounds; document.getElementById('tip').innerHTML = '您当前所在城市:'+cityinfo; } } else { document.getElementById('tip').innerHTML = result.info; } }); } </script> </body> </html>
在线示例:http://zhaoziang.com/amap/nomapGetcity.htm