【百度地图API】暑假放假回老家——城市切换功能

任务描述:

  酸奶小妹放寒假啦,要从北京呼啦一下飞回重庆呢。现在百度地图API上不能直接切换城市,怎么办呢?

 

如何实现:

  利用API先搜索到要去城市,然后再让搜索到的城市显示在地图中心点。

  (百度地图上的实现方式是,给后端一个请求,后端返回该城市的经纬度)

 

图示:

 

运行代码:请点击这里

 

代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312"/>
<meta name="keywords" content="百度地图,百度地图API,百度地图自定义工具,百度地图所见即所得工具"/>
<meta name="description" content="百度地图API自定义地图,帮助用户在可视化操作下生成百度地图"/>
<title>从北京到重庆</title>
<script type="text/javascript" src="http://api.map.baidu.com/api?&v=1.2">
</script>
</head>
<body> 
<p>我要去<input id="txtSearch" type="text" value="重庆"/><input type="button" value="GO" οnclick="search()"/></p>
<div style="width:520px;height:340px;border:1px solid gray;" id="container"></div>
</body>
<script type="text/javascript">
function $(id){
  return document.getElementById(id);   //定义$
}
var map =new BMap.Map("container");    //创建地图
map.centerAndZoom(new BMap.Point(116.330599, 39.95536), 10);      //初始化地图

var city =new BMap.LocalSearch(map,{renderOptions:{map:map,autoViewport:true}});   //地图显示到查询结果处

function search(){
  var s = $("txtSearch").value;
  city.search(s);   //查找城市
}
</script>
</html>

2012-02-07  更新一下API1.2的代码:

原理:localsearch关键词,比如“西单”。

在回调函数里,获取第一个POI的经纬度,并且该点为中心点。

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>西单</title>
<script type="text/javascript" src="http://api.map.baidu.com/api?v=1.2"></script>
</head>
<body>
<div style="width:520px;height:340px;border:1px solid gray" id="container"></div>
</body>
</html>
<script type="text/javascript">
var map = new BMap.Map("container");
map.centerAndZoom(new BMap.Point(116.404, 39.915), 11);

function myFun(){
    var pp = local.getResults().getPoi(0).point;
    map.centerAndZoom(pp, 18);
}
var local = new BMap.LocalSearch(map, {
  onSearchComplete: myFun
});
local.search("西单");
</script>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值