如何結合自己本地數據庫,使用【百度地圖】API
百度地圖使用越來越多,官網上的示例數據都是寫死的,實際上我們的開發中的數據都是從數據庫中取出來的,最近看了很多大神的文章,結合自己本地數據庫使用百度地圖API,這里來總結一下具體的代碼。
本示例中,實現了將數據庫里的位置信息顯示在地圖中,還實現了基本的搜索功能。
這里需要用到:請將這些庫提前准備好放到文件中
jquery.min.js
與后台交互:Ajax 技術
另外用到:MySQL+PHP (沒有基礎也沒事,后面附有)
注意使用前先到官網申請秘鑰
實例文件目錄為:
|-config
|-conn.php 連接數據庫
|-search_action.php 實現文本框搜索
|-css
|-app.css
|-js
|-index.js Ajax與后台交互代碼
|-jquery.min.js
|-header.php 將公共的頭部信息分出來
|-index.php 首頁顯示地圖
1.創建數據庫,SQL語句:
create database map CHARSET=utf8;
use map;
2.創建表格,SQL語句:
CREATE TABLE IF NOT EXISTS `myMap` (
`id` int(11) NOT NULL,
`point` varchar(128) NOT NULL,
`title` varchar(128) NOT NULL,
`address` varchar(128) NOT NULL,
`price` float NOT NULL,
`tel` varchar(20) NOT NULL,
`level` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
可以利用百度地圖提供的坐標拾撿工具:http://api.map.baidu.com/lbsapi/getpoint/
獲取坐標。
3.插入數據:
這里我們准備了10條自己的數據,id是按順序插入的
SQL語句:
INSERT INTO `myMap` (`id`, `point`, `title`, `address`, `price`, `tel`, `level`) VALUES
(0, '116.411776,39.942833', '如家快捷酒店', '北京市朝陽區高碑店小學旁', 120, '010-59921010', 5),
(1, '116.320791,40.003682', '昆侖大廈', '北京市海淀區紫竹院123號', 2370, '010-59921010', 4),
(2, '116.275186,39.896095', '華夏銀行', '北京市海淀區紫竹院123號', 50, '010-59921010', 4),
(3, '116.425098,39.946249', '成都小吃', '北京市海淀區紫竹院123號', 16, '010-59921010', 4),
(4, '116.359823,39.984761', '錦綉大飯店', '北京市朝陽區高碑店小學旁', 300, '010-59921010', 5),
(5, '116.316479,39.98323', '七天快捷酒店', '北京市大鍾寺滄瀾大廈', 180, '010-59921010', 5),
(6, '116.385986,39.946124', '中央民族大學', '北京市朝陽區高碑店小學旁', 9, '010-59921010', 3),
(7, '116.427545,40.00796', '昌平汽車專修學院', '北京市哇哈哈路鮮魚一條街', 3300, '010-59921010', 3),
(8, '116.446965,39.911603', '百度大廈', '北京市朝陽區高碑店小學旁', 20, '010-59921010', 3),
(9, '116.454579,39.946652', '海爾電器銷售點', '北京市朝陽區高碑店小學旁', 1000, '010-59921010', 3);
4.css/app.css代碼為:
1 *{
2 padding: 0;
3 margin: 0;
4 }
5
6 #container {
7 float:left;
8 width:800px;
9 height:500px;
10 border:1px solid gray;
11 display: block;
12 }
13
14 .search_box {
15 position: relative;
16 width: 500px;
17 float: right;
18 }
19 #search{
20 border: 1px solid #ccc;
21 width:220px;
22 height:25px;
23 text-indent:3px;
24 }
25 .search_results {
26 border: 1px solid #ccc;
27 height: auto;
28 max-height: 200px;
29 overflow-y: scroll;
30 width: 220px;
31 position: relative;
32 display: none;
33 }
34
35 .search_results > li {
36 color: #333;
37 font-size: 14px;
38 height: 30px;
39 line-height: 30px;
40 list-style: outside none none;
41 text-indent: 10px;
42 }
43 .search_results > li:hover {
44 background: #f2f2f2;
45 }
46 .search_results a {
47 text-decoration: none;
48 color: #333;
49 }
5.連接數據庫,查詢數據,config/conn.php代碼為:
<?
// 連接到數據庫
$conn = new mysqli("localhost", "root","","map")
or die("Could not connect: ".mysql_error());
mysqli_query($conn,"set names 'utf8'");
?>
6. header.php 的代碼為:
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>Document</title>
6 <link rel="stylesheet" type="text/css" href="css/app.css">
7 <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=piXQ5CgHFqEefqCVbhhBFfe6HjF7l4zW"></script>
8 <!-- 控制區域顯示js -->
9 <script type="text/javascript" src="http://api.map.baidu.com/library/AreaRestriction/1.2/src/AreaRestriction_min.js"></script>
10
11 </head>
12 <body>
7. 獲取查詢結果,對獲取結果進行處理,這里1.創建坐標,2.創建標注,3.將標注添加到地圖中,4.自定義窗口信息,5.創建窗口對象,6.為創建的標注綁定mouseover事件。
index.php 的代碼為:
1 <? include ('header.php') ?>
2 <div id="container"></div>
3 <div class="search_box">
4 <form method="post">
5 <div>輸入搜索的內容:</div><input type="text" id="search" name="topic" autocomplete="off" placeholder="請輸入序號,地址,或名稱查詢">
6 </form>
7 <ul class="search_results"></ul>
8 </div>
9
10 <? include ('config/conn.php') ?>
11 <?php 12 $strsql="select * from myMap" ; 13 $result = $conn->query($strsql); 14
15 // 獲取查詢結果
16 $arr_point = '['; 17 $maker = ''; 18 $addverlay=''; 19 $ops = ''; 20 $infoWindow=''; 21 $addEventListener=''; 22 $i = 0; 23 // $addverlay = ''; //修改php.ini的error_reporting = E_ALL為error_reporting = E_ALL & ~E_NOTICE
24
25 while ($row = $result->fetch_assoc()) { 26 $img = ''; 27
28 //1.從數據庫中獲取坐標,創建地圖上的坐標點,並把它放到數組里
29 $arr_point .= 'new BMap.Point('.$row["point"].'),'; 30
31 //2.利用這些坐標點創建標注mark1-mark9,將標注都存放到變量$mark中
32 $maker .= 'var marker'.$i.' = new BMap.Marker(point['.$i.']);'; 33
34 //3.將標注添加到地圖中
35 $addverlay .= 'map.addOverlay(marker'.$i.');'; 36 for($m = 0;$m < $row["level"];$m++){ 37 $img .= "<img src='http://cdn2.iconfinder.com/data/icons/diagona/icon/16/031.png' />"; 38 } 39
40 //4.信息窗口的標題,記住,要先定義opts,再定義信息窗口
41 $ops .= 'var opts'.$i.' = {title : \'<span style="font-size:14px;color:#0A8021">'.$row['title'].'</span>\'};'; 42
43 //5.創建信息窗口對象,信息窗口接收兩個參數,第一個並指信息窗口的內容,第二個指上面定義的opts. 信息窗口里支持任意的htm代碼
44 $infoWindow .= "var infoWindow".$i." = new BMap.InfoWindow(\"<div style='line-height:1.8em;font-size:12px;'><b>地址:</b>".$row['address']."</br><b>電話:</b>010-59921010</br><b>口碑:</b>".$img."<a style='text-decoration:none;color:#2679BA;float:right' href='#'>詳情>></a></div>\", opts".$i.");"; 45
46 //6.給每一個標注添加mouseover事件
47 $addEventListener .= 'marker'.$i.'.addEventListener("mouseover", function(){this.openInfoWindow(infoWindow'.$i.');});'; 48 $i++; 49 } 50 $arr_point .= substr($arr_point , 0 , -1).']]'; 51 ?>
52 <script type="text/javascript">
53 var map = new BMap.Map("container"); // 創建Map實例
54 var point = new BMap.Point(116.404, 39.915); //創建中心點坐標
55 map.centerAndZoom(point, 14); //初始化地圖,設置中心點坐標和地圖級別
56
57 function openMyWin(id,p){ 58 map.openInfoWindow(id,p); 59 } 60 </script>
61
62 <!-- 定義好信息后,需要把js用php語句拼起來 -->
63 <?php 64 echo '<script> var point = '.$arr_point.';'; //坐標點
65 echo $maker; //創建標注
66 echo $addverlay; //將標注添加到地圖中
67 echo 'map.setViewport(point); '; // 調整地圖的最佳視野為顯示標注數組point
68 echo $ops; 69 echo $infoWindow ; 70 echo $addEventListener.' </script> '
71 ?>
72 <script type="text/javascript" src="js/jquery.2.1.1.min.js"></script>
73 <!-- 文本框搜索交互代碼 -->
74 <script type="text/javascript" src="js/index.js"></script>
75 </body>
76 </html>
8.下面是文本框的搜索:
編寫的ajax交互代碼放到 js/index.js里面,代碼如下:
1 $(function(){ 2 $('#search').val(''); 3 $(window).click(function(event) { 4 $('.search_results').css('display','none'); 5 }); 6 $('#search, .search_results li').click(function(e) { 7 e.stopPropagation(); 8 }); 9 $('#search').keyup(function(event) { 10 event.stopPropagation(); 11 $.ajax({ 12 url: 'config/search_action.php', 13 type: 'post', 14 data: $("form").serialize(), 15 success: function(responseText,status,xhr){ 16 console.log(responseText); 17 if (responseText != ''){ 18 $('.search_results').css('display','block'); 19 $('.search_results').html(responseText); 20 } else { 21 $('.search_results').html("<li>沒有搜索到</li>"); 22 } 23
24 } 25 }) 26 .done(function() { 27 console.log("success"); 28 }) 29 .fail(function() { 30 console.log("error"); 31 }) 32 .always(function() { 33 console.log("complete"); 34 }); 35 ; 36 }); 37 });
9.請求的后台文件為config/search_action.php,代碼為:
1 <? include ('conn.php') ?>
2 <?
3 $subject = $_POST['topic']; 4 if ($subject != ''){ 5 $search_sql = "select * from y_map where (id like '%" .$subject. "%') or (title like '%" .$subject. "%') or (address like '%" .$subject. "%') order by id,title,address"; 6 $search_result = mysqli_query($conn, $search_sql); 7 while ($row = $search_result->fetch_assoc()) { 8 echo '<li onmouseover="openMyWin(infoWindow'.$row["id"].',point['.$row["id"].'])" > 9 <a href="#">'.$row['title'].'</a> 10 </li>'; 11 } 12 } else { 13 echo "none result"; 14 } 15 ?>
10.總結:
使用百度地圖的基本步驟:
1.創建地圖實例:var map = new BMap.Map("container");
2.創建中心點坐標:var point = new BMap.Point(116.404, 39.915);
3.初始化地圖,設置中心點坐標和地圖級別:map.centerAndZoom(point, 14);
5.獲取坐標點:
如: var points = [
new BMap.Point(116.411776,39.942833),
new BMap.Point(116.320791,40.003682)
];
6.創建標注:
如:var marker1 =new BMap.Marker(points[1]);
var marker2 =new BMap.Marker(points[2]);
7.將標注添加到地圖中:
如:map.addOverlay(marker1);
map.addOverlay(marker2);
8.調整地圖的最佳視野為顯示標注數組point:
如:map.setViewport(points);