Laravel 引入百度地图api,手机打开页面通过浏览器自动定位,手动校准定位,搜索位置定位,实例

love-snow · · 69 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

百度地图api,手机打开页面自动定位,手动校准定位,搜索位置定位,实例

 

1、JavaScript API

地址:http://lbsyun.baidu.com/index.php?title=jspopular

注册百度账号,通过上边的开发指南,获取秘钥AK;

2、这里用Laravel 举例说明

Laravel 通过运行如下命令可快速生成认证所需要的路由和视图:

php artisan make:auth

目录下包含了应用的基础布局文件。所有这些视图都使用了 Bootstrap CSS 框架,你也可以根据需要对其进行自定义。

修改 resources/views/layouts/app.blade.php:

<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>

    <!-- Styles -->
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
    <link href="{{ asset('css/loader.css') }}" rel="stylesheet">
    <script src="http://api.map.baidu.com/api?v=2.0&ak=这里写上你的百度AK"></script>
    <style type="text/css">
        body{
            font-family: '微软雅黑';
        }
        #baidu_map{
            width:300px;height:200px;overflow:hidden;margin:0;font-family:"微软雅黑";
        }
    </style>
</head>
<body>
    <div id="app">
        <nav class="navbar navbar-default navbar-static-top">
            <div class="container">
                <div class="navbar-header">

                    <!-- Collapsed Hamburger -->
                    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#app-navbar-collapse">
                        <span class="sr-only">侧边栏导航</span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>

                    <!-- Branding Image -->
                    <a class="navbar-brand" href="{{ url('/') }}">
                        {{ config('app.name', 'Laravel') }}
                    </a>
                </div>

                <div class="collapse navbar-collapse" id="app-navbar-collapse">
                    <!-- Left Side Of Navbar -->
                    <ul class="nav navbar-nav">
                        &nbsp;
                    </ul>

                    <!-- Right Side Of Navbar -->
                    <ul class="nav navbar-nav navbar-right">
                        <!-- Authentication Links -->
                        @guest
                            <!-- <li><a href="{{ route('login') }}">登陆</a></li>
                            <li><a href="{{ route('register') }}">注册</a></li> -->
                        @else
                            <li class="dropdown">
                                <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
                                    {{ Auth::user()->name }} <span class="caret"></span>
                                </a>

                                <ul class="dropdown-menu" role="menu">
                                    <li>
                                        <a href="{{ route('logout') }}"
                                            onclick="event.preventDefault();
                                                     document.getElementById('logout-form').submit();">
                                            退出
                                        </a>

                                        <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
                                            {{ csrf_field() }}
                                        </form>
                                    </li>
                                </ul>
                            </li>
                        @endguest
                    </ul>
                </div>
            </div>
        </nav>

        @yield('content')
    </div>

    <!-- Scripts -->
    <script src="{{ asset('js/app.js') }}"></script>
</body>
</html>

loader.css文件如下:

.chromeframe {
    margin: 0.2em 0;
    background: #ccc;
    color: #000;
    padding: 0.2em 0;}
#loader-wrapper {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index:999999;}
#loader {
    display: block;
    position: relative;
    left: 50%;
    top: 50%;
    width: 150px;
    height: 150px;
    margin: -75px 0 0 -75px;
    border-radius: 50%;
    border: 3px solid transparent;
    /* COLOR 1 */
    border-top-color: #FFF;
    border-bottom-color: #FFF;
    -webkit-animation: spin 2s linear infinite; /* Chrome, Opera 15+, Safari 5+ */
    -ms-animation: spin 2s linear infinite; /* Chrome, Opera 15+, Safari 5+ */
    -moz-animation: spin 2s linear infinite; /* Chrome, Opera 15+, Safari 5+ */ 
    -o-animation: spin 2s linear infinite; /* Chrome, Opera 15+, Safari 5+ */   
        animation: spin 2s linear infinite; /* Chrome, Firefox 16+, IE 10+, Opera */
    z-index:1001;
}
#loader > div {
        content: "";
        position: absolute;
        top: 45px;
        left: 45px;
        right: 45px;
        bottom: 45px;
        border-radius: 50%;
        border: 3px solid transparent;

        /* COLOR 2 */       
        border-top-color: #FFF;
        border-bottom-color: #FFF;
        -webkit-animation: spin 3s linear infinite; /* Chrome, Opera 15+, Safari 5+ */
        -moz-animation: spin 3s linear infinite; /* Chrome, Opera 15+, Safari 5+ */
        -o-animation: spin 3s linear infinite; /* Chrome, Opera 15+, Safari 5+ */
        -ms-animation: spin 3s linear infinite; /* Chrome, Opera 15+, Safari 5+ */              
        animation: spin 3s linear infinite; /* Chrome, Firefox 16+, IE 10+, Opera */
}
#loader:before {
        content: "";
        position: absolute;
        top: 8px;
        left: 8px;
        right: 8px;
        bottom: 8px;
        border-radius: 50%;
        border: 3px solid transparent;

        /* COLOR 2 */       
        border-top-color: #FFF;
        border-bottom-color: #FFF;
        -webkit-animation: spin 3s linear infinite; /* Chrome, Opera 15+, Safari 5+ */
        -moz-animation: spin 3s linear infinite; /* Chrome, Opera 15+, Safari 5+ */
        -o-animation: spin 3s linear infinite; /* Chrome, Opera 15+, Safari 5+ */
        -ms-animation: spin 3s linear infinite; /* Chrome, Opera 15+, Safari 5+ */              
        animation: spin 3s linear infinite; /* Chrome, Firefox 16+, IE 10+, Opera */
}
#loader:after {
        content: "";
        position: absolute;
        top: 19px;
        left: 19px;
        right: 19px;
        bottom: 19px;
        border-radius: 50%;
        border: 3px solid transparent;
        border-top-color: #FFF;
        border-bottom-color: #FFF;
        /* COLOR 3 */       
        -moz-animation: spin 1.5s linear infinite; /* Chrome, Opera 15+, Safari 5+ */
        -o-animation: spin 1.5s linear infinite; /* Chrome, Opera 15+, Safari 5+ */
        -ms-animation: spin 1.5s linear infinite; /* Chrome, Opera 15+, Safari 5+ */        
        -webkit-animation: spin 1.5s linear infinite; /* Chrome, Opera 15+, Safari 5+ */
          animation: spin 1.5s linear infinite; /* Chrome, Firefox 16+, IE 10+, Opera */}


@-webkit-keyframes spin {
        0%{ 
            -webkit-transform: rotate(0deg);  /* Chrome, Opera 15+, Safari 3.1+ */
            -ms-transform: rotate(0deg);  /* IE 9 */
            transform: rotate(0deg);  /* Firefox 16+, IE 10+, Opera */
        }100%{
            -webkit-transform: rotate(360deg);  /* Chrome, Opera 15+, Safari 3.1+ */
            -ms-transform: rotate(360deg);  /* IE 9 */
            transform: rotate(360deg);  /* Firefox 16+, IE 10+, Opera */}
}

@keyframes spin {
        0%{ 
            -webkit-transform: rotate(0deg);  /* Chrome, Opera 15+, Safari 3.1+ */
            -ms-transform: rotate(0deg);  /* IE 9 */
            transform: rotate(0deg);  /* Firefox 16+, IE 10+, Opera */
        }100%{
            -webkit-transform: rotate(360deg);  /* Chrome, Opera 15+, Safari 3.1+ */
            -ms-transform: rotate(360deg);  /* IE 9 */
            transform: rotate(360deg);  /* Firefox 16+, IE 10+, Opera */}
}


#loader-wrapper .loader-section {
        position: fixed;
        top: 0;
        width: 51%;
        height: 100%;
        background: #2579a9; /* Old browsers */
        z-index: 1000;
        -webkit-transform: translateX(0);  /* Chrome, Opera 15+, Safari 3.1+ */
        -ms-transform: translateX(0);  /* IE 9 */
        transform: translateX(0);  /* Firefox 16+, IE 10+, Opera */}
#loader-wrapper .loader-section.section-left {left: 0;}
#loader-wrapper .loader-section.section-right {right: 0;}

/* Loaded */
.loaded #loader-wrapper .loader-section.section-left {
        -webkit-transform: translateX(-100%);  /* Chrome, Opera 15+, Safari 3.1+ */
            -ms-transform: translateX(-100%);  /* IE 9 */
                transform: translateX(-100%);  /* Firefox 16+, IE 10+, Opera */
        -webkit-transition: all 0.7s 0.3s cubic-bezier(0.645, 0.045, 0.355, 1.000);  
                transition: all 0.7s 0.3s cubic-bezier(0.645, 0.045, 0.355, 1.000);}
.loaded #loader-wrapper .loader-section.section-right {
        -webkit-transform: translateX(100%);  /* Chrome, Opera 15+, Safari 3.1+ */
            -ms-transform: translateX(100%);  /* IE 9 */
                transform: translateX(100%);  /* Firefox 16+, IE 10+, Opera */
        -webkit-transition: all 0.7s 0.3s cubic-bezier(0.645, 0.045, 0.355, 1.000);  
        transition: all 0.7s 0.3s cubic-bezier(0.645, 0.045, 0.355, 1.000);}
.loaded #loader {
        opacity: 0;
        -webkit-transition: all 0.3s ease-out;  
                transition: all 0.3s ease-out;}
.loaded #loader-wrapper {
        visibility: hidden;
        -webkit-transform: translateY(-100%);  /* Chrome, Opera 15+, Safari 3.1+ */
            -ms-transform: translateY(-100%);  /* IE 9 */
                transform: translateY(-100%);  /* Firefox 16+, IE 10+, Opera */
        -webkit-transition: all 0.3s 1s ease-out;  
                transition: all 0.3s 1s ease-out;}
/* JavaScript Turned Off */
.no-js #loader-wrapper {display: none;}
.no-js h1 {color: #222222;}
#loader-wrapper .load_title {
    font-family:'微软雅黑';
    color:#FFF; 
    font-size:19px; 
    width:100%; 
    text-align:center; 
    z-index:9999999999999; 
    position:absolute; 
    top:65%; 
    opacity:1; 
    line-height:30px; }
#loader-wrapper .load_title span {  font-weight:normal; font-style:italic; font-size:13px; color:#FFF; opacity:0.5;}

创建一个你的定位的视图文件,位置自己定义:

@extends('layouts.app')

@section('content')

<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                <div class="panel-heading">定位</div>
                <div class="panel-body">
                        <form class="form-horizontal" method="POST" action="#">
                            {{ csrf_field() }}
                            
                            <div class="form-group{{ $errors->has('longitude') ? ' has-error' : '' }}">
                                <label for="longitude" class="col-md-4 control-label">经度:</label>

                                <div class="col-md-6">
                                    <input id="longitude" type="text" class="form-control" name="longitude" value="" required readonly>

                                    @if ($errors->has('longitude'))
                                        <span class="help-block">
                                            <strong>{{ $errors->first('longitude') }}</strong>
                                        </span>
                                    @endif
                                </div>
                            </div>

                            <div class="form-group{{ $errors->has('latitude') ? ' has-error' : '' }}">
                                <label for="latitude" class="col-md-4 control-label">纬度:</label>

                                <div class="col-md-6">
                                    <input id="latitude" type="text" class="form-control" name="latitude" value="" required readonly />

                                    @if ($errors->has('latitude'))
                                        <span class="help-block">
                                            <strong>{{ $errors->first('latitude') }}</strong>
                                        </span>
                                    @endif
                                </div>
                            </div>

                            <div class="form-group{{ $errors->has('province') ? ' has-error' : '' }}">
                                <label for="province" class="col-md-4 control-label">省份:</label>

                                <div class="col-md-6">
                                    <input id="province" type="text" class="form-control" name="province" value="" required readonly />

                                    @if ($errors->has('province'))
                                        <span class="help-block">
                                            <strong>{{ $errors->first('province') }}</strong>
                                        </span>
                                    @endif
                                </div>
                            </div>

                            <div class="form-group{{ $errors->has('city') ? ' has-error' : '' }}">
                                <label for="city" class="col-md-4 control-label">市:</label>

                                <div class="col-md-6">
                                    <input id="city" type="text" class="form-control" name="city" value="" required readonly />

                                    @if ($errors->has('city'))
                                        <span class="help-block">
                                            <strong>{{ $errors->first('city') }}</strong>
                                        </span>
                                    @endif
                                </div>
                            </div>

                            <div class="form-group{{ $errors->has('district') ? ' has-error' : '' }}">
                                <label for="district" class="col-md-4 control-label">县/区:</label>

                                <div class="col-md-6">
                                    <input id="district" type="text" class="form-control" name="district" value="" required readonly />

                                    @if ($errors->has('district'))
                                        <span class="help-block">
                                            <strong>{{ $errors->first('district') }}</strong>
                                        </span>
                                    @endif
                                </div>
                            </div>

                            <div class="form-group{{ $errors->has('address') ? ' has-error' : '' }}">
                                <label for="address" class="col-md-4 control-label">详细地址:</label>

                                <div class="col-md-6">
                                    <input id="address" type="text" class="form-control" name="address" required />

                                    @if ($errors->has('address'))
                                        <span class="help-block">
                                            <strong>{{ $errors->first('address') }}</strong>
                                        </span>
                                    @endif
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="address" class="col-md-4 control-label">搜索位置:</label>
                                
                                <div class="col-md-6">
                                    <input type="text" id="suggestId" class="form-control" name="description" placeholder="如果定位有偏差,在这里手动搜索地址" />
                                    <div id="searchResultPanel" style="border:1px solid #C0C0C0;width:150px;height:auto; display:none;"></div>
                                </div>
                            </div>

                            <div class="form-group">
                                <div class="col-md-6 col-md-offset-4">
                                   <div><font color= #f4645f>*如果定位有偏差可以手动点击屏幕校准,也可以根据搜索框进行搜索</font></div>
                                </div>
                            </div>
                            <div class="form-group{{ $errors->has('province') ? ' has-error' : '' }}">
                                <label for="province" class="col-md-4 control-label">地图定位:</label>

                                <div class="col-md-6">
                                    <div id="baidu_map"></div>
                                </div>
                            </div>

                            <div class="form-group">
                                <div class="col-md-6 col-md-offset-4">
                                    <button type="submit" class="btn btn-primary btn-block">
                                        提交
                                    </button>
                                </div>
                            </div>
                        </form>
                        <div id="loader-wrapper">
                            <div id="loader"><div></div></div>
                            <div class="loader-section section-left"></div>
                            <div class="loader-section section-right"></div>
                            <div class="load_title">正在定位...</div>
                        </div>
                    @endif    
                </div>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">
    window.onload = function () {
        location.href = "#baidu_map";
        function G(id) {
            return document.getElementById(id);
        }
        var longitude = G('longitude')
        var latitude  = G('latitude');
        var province  = G('province');
        var city      = G('city');
        var district  = G('district');
        var address   = G('address');
        // 百度地图API功能
        var map       = new BMap.Map("baidu_map");    // 创建Map实例
        var point     = new BMap.Point(116.404, 39.915);
        var myIcon    = new BMap.Icon("http://api.map.baidu.com/img/markers.png", new BMap.Size(22, 24), {
            offset: new BMap.Size(12, 20), // 指定定位位置
            imageOffset: new BMap.Size(1, 0 - 12 * 25) // 设置图片偏移
        });
        var setMarker = function(point){
            map.clearOverlays();//清楚所有标注点
            var marker = new BMap.Marker(point,{icon:myIcon}); 
            marker.setAnimation(BMAP_ANIMATION_BOUNCE);
            map.addOverlay(marker);
        }
        var getInfo = function(point){
            var geoc = new BMap.Geocoder();
            geoc.getLocation(point, function(rs){
                var addComp     = rs.addressComponents;
                province.value  = addComp.province;
                city.value      = addComp.city;
                district.value  = addComp.district;
                address.value   = rs.address;
                longitude.value = point.lng;
                latitude.value  = point.lat;
            });
        }
        map.centerAndZoom(point, 18);  // 初始化地图,设置中心点坐标和地图级别
        map.setDefaultCursor("url('bird.cur')");   //设置地图默认的鼠标指针样式
        map.enableScrollWheelZoom(true);//开启鼠标滚轮缩放       
        
        setMarker(point);
        //自动定位
        var geolocation = new BMap.Geolocation();
        geolocation.getCurrentPosition(function(r){
            $('body').addClass('loaded');
            $('#loader-wrapper .load_title').remove();
            if(this.getStatus() == BMAP_STATUS_SUCCESS){
                setMarker(r.point);
                map.panTo(r.point);
                getInfo(r.point);
            }      
        },{enableHighAccuracy: true});
        
        // 添加定位控件
        var geolocationControl = new BMap.GeolocationControl({
            'anchor':BMAP_ANCHOR_BOTTOM_RIGHT,//设置控件的停靠位置,默认定位到地图的左下角
            'locationIcon':myIcon,//可自定义定位中心点的Icon样式
            'enableAutoLocation':true //添加控件时是否进行定位。默认添加控件时不进行定位
        });
        geolocationControl.addEventListener("locationSuccess", function(e){
            // 定位成功事件
            setMarker(e.point);
            getInfo(e.point);
            map.panTo(e.point);
            map.centerAndZoom(e.point, 18);
        });
        geolocationControl.addEventListener("locationError",function(e){
            alert(e.message);// 定位失败事件
        });
        
        //单击矫正定位
        map.addEventListener("click", function(e){
            setMarker(e.point);
            getInfo(e.point);
        });

        map.addControl(geolocationControl);//添加定位控件

        //搜索定位
        //建立一个自动完成的对象
        var ac = new BMap.Autocomplete({
            "input" : "suggestId",
            "location" : map
        });
        //鼠标放在下拉列表上的事件
        ac.addEventListener("onhighlight", function(e) {  
            var str    = "";
            var _value = e.fromitem.value;
            var value  = "";
            if (e.fromitem.index > -1) {
                value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
            }    
            str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;
            
            value = "";
            if (e.toitem.index > -1) {
                _value = e.toitem.value;
                value  = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
            }    
            str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
            G("searchResultPanel").innerHTML = str;
        });
        var myValue;
        //鼠标点击下拉列表后的事件
        ac.addEventListener("onconfirm", function(e) {
            var _value = e.item.value;
            myValue    = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
            G("searchResultPanel").innerHTML ="onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;
            setPlace();
        });
        function setPlace(){
            function myFun(){
                var point = local.getResults().getPoi(0).point;//获取第一个智能搜索的结果
                getInfo(point);
                setMarker(point);
                map.centerAndZoom(point, 18);
            }
            //智能搜索
            var local = new BMap.LocalSearch(map, { 
              onSearchComplete: myFun
            });
            local.search(myValue);
        }
    }
</script>
@endsection

 

69 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet