关于google地图的一些使用

1、注册google账号(开发文档地址:https://developers.google.com/maps/gmp-get-started

  通过上面文档地址可以创建apikey,及添加自己的使用接口

2、真实示例

   1、打开页面获取当前用户地理位置

     js代码:

​​​​​​​var map, infoWindow;
    function initMap() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
                console.log(position);
                var pos = {
                    lat: position.coords.latitude,
                    lng: position.coords.longitude
                };
                $.ajax({
                    type : "post",
                    url : "{:__URL('APP_MAIN/Index/nearShop')}",
                    data : pos,
                    success : function(data) {
                       console.log(data);
                       $("#shopname").html(data.shopname);
                    }
                })
                // console.log(pos);
                // infoWindow.setPosition(pos);
                // infoWindow.setContent('Location found.');
                // infoWindow.open(map);
                // map.setCenter(pos);
            }, function (error) {
//处理错误
                console.log(error);
                switch (error.code) {
                    case 1:
                        alert("位置服务被拒绝。");
                        break;
                    case 2:
                        alert("暂时获取不到位置信息。");
                        break;
                    case 3:
                        alert("获取信息超时。");
                        break;
                    default:
                        alert("未知错误。");
                        break;
                }
            });
        } else {
            // Browser doesn't support Geolocation
            handleLocationError(false, infoWindow, map.getCenter());
        }
    }

    引入js文件:

<script async defer
        src="https://maps.googleapis.com/maps/api/js?key={$googlekey}&callback=initMap">
</script>

2、通过输入的地址获取经纬度

html代码:

<input type="hidden" name="address_lng" value="" id="address_lng">
<input type="hidden" name="address_lat" value="" id="address_lat">

js代码:

<script type="text/javascript">
   var lngtxt = "-79.33701880000001";
   var lattxt = "343.85610020000001";
   var addresstxt = "万锦安大略省加拿大";
   var map;
   var marker;
   var infowindow;
   var geocoder;
   var markersArray = [];

   function initAutocomplete() {
      var input = document.getElementById('pac-input');
      var searchBox = new google.maps.places.SearchBox(input);
      var markers = [];
      // Listen for the event fired when the user selects a prediction and retrieve
      // more details for that place.
      searchBox.addListener('places_changed', function() {
         var places = searchBox.getPlaces();

         if(places.length == 0) {
            return;
         }

         // Clear out the old markers.
         markers.forEach(function(marker) {
            marker.setMap(null);
         });
         markers = [];

         // For each place, get the icon, name and location.
         var bounds = new google.maps.LatLngBounds();
         places.forEach(function(place) {
            if(!place.geometry) {
               console.log("Returned place contains no geometry");
               return;
            }
            mapClick(place.geometry.location.lng(), place.geometry.location.lat(), place.name);
         });
      });
   }
   function mapClick(lng, lat, address) {
      window.parent.document.getElementById("address_lng").value = lng;
      window.parent.document.getElementById("address_lat").value = lat;
      window.parent.document.getElementById("pac-input").value = address;
      var shop_name = address;
      var address_lng = lng;
      var address_lat = lat;
      window.location.href="/wap/Index/select_community?shop_name="+shop_name+'&address_lng='+address_lng+'&address_lat='+address_lat;
   }
</script>

引入js文件: 

<script src="https://maps.googleapis.com/maps/api/js?key={$googlekey}&libraries=places&callback=initAutocomplete" async defer></script>

后台显示地图及根据地址获取经纬度:

  html代码:

                <dl>
                    <dt><i class="required">*</i>门店地址:</dt>
                    <dd>
                        <input class="productname input-common" id="pac-input" type='text' name="shop_address_two" value=""
                               placeholder="Search Box"/>
                        <input type="hidden" id="address">
                        <div id="map" style="width:700px; height:400px"></div>
                    </dd>
                </dl>
                <dl>
                    <dt> <i class="required">*</i>经纬度:</dt>
                    <dd>
                        <input id="address_lng" name="shop_lonlat2" type="text" placeholder="" value="" class="input-common harf">
                        <input id="address_lat" name="shop_lonlat1" type="text" placeholder="" value="" class="input-common harf">
                    </dd>
                </dl>

js代码:

<script type="text/javascript">
    // var lngtxt = "101.686855";
    // var lattxt = "3.139003";
    // var addresstxt = "吉隆坡";
    var lngtxt = "{$data['shop_lon']}";
    var lattxt = "{$data['shop_lat']}";
    var addresstxt = "{$data['shop_address']}";
    var map;
    var marker;
    var infowindow;
    var geocoder;
    var markersArray = [];

    function initAutocomplete() {
        var latlng = new google.maps.LatLng(lattxt, lngtxt);
        var myOptions = {
            zoom: 13,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById('map'), myOptions);

        geocoder = new google.maps.Geocoder(); //实例化地址解析
        //监听点击地图事件
        google.maps.event.addListener(map, 'click', function(event) {
            placeMarker(event.latLng);
        });
        // Create the search box and link it to the UI element.
        var input = document.getElementById('pac-input');
        var searchBox = new google.maps.places.SearchBox(input);
        map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

        // Bias the SearchBox results towards current map's viewport.
        map.addListener('bounds_changed', function() {
            searchBox.setBounds(map.getBounds());
        });

        var markers = [];
        // Listen for the event fired when the user selects a prediction and retrieve
        // more details for that place.
        searchBox.addListener('places_changed', function() {
            var places = searchBox.getPlaces();

            if(places.length == 0) {
                return;
            }

            // Clear out the old markers.
            markers.forEach(function(marker) {
                marker.setMap(null);
            });
            markers = [];

            // For each place, get the icon, name and location.
            var bounds = new google.maps.LatLngBounds();
            places.forEach(function(place) {
                if(!place.geometry) {
                    console.log("Returned place contains no geometry");
                    return;
                }
                var icon = {
                    url: place.icon,
                    size: new google.maps.Size(71, 71),
                    origin: new google.maps.Point(0, 0),
                    anchor: new google.maps.Point(17, 34),
                    scaledSize: new google.maps.Size(25, 25)
                };
                //console.log(place.geometry.location.lat());
                mapClick(place.geometry.location.lng(), place.geometry.location.lat(), place.name);
                // Create a marker for each place.
                markers.push(new google.maps.Marker({
                    map: map,
                    icon: icon,
                    title: place.name,
                    position: place.geometry.location
                }));

                if(place.geometry.viewport) {
                    // Only geocodes have viewport.
                    bounds.union(place.geometry.viewport);
                } else {
                    bounds.extend(place.geometry.location);
                }
            });
            map.fitBounds(bounds);
        });
    }

    function placeMarker(location) {
        clearOverlays(infowindow); //清除地图中的标记
        marker = new google.maps.Marker({
            position: location,
            map: map
        });
        markersArray.push(marker);
        //根据经纬度获取地址
        if(geocoder) {
            geocoder.geocode({
                'location': location
            }, function(results, status) {
                if(status == google.maps.GeocoderStatus.OK) {
                    if(results[0]) {
                        attachSecretMessage(marker, results[0].geometry.location, results[0].formatted_address);
                    }
                } else {
                    alert("Geocoder failed due to: " + status);
                }
            });
        }
    }
    //在地图上显示经纬度地址
    function attachSecretMessage(marker, piont, address) {
        var message = "<b>坐标:</b>" + piont.lat() + " , " + piont.lng() + "<br />" + "<b>地址:</b>" + address;
        var infowindow = new google.maps.InfoWindow({
            content: message,
            size: new google.maps.Size(50, 50)
        });
        infowindow.open(map, marker);
        if(typeof(mapClick) == "function") mapClick(piont.lng(), piont.lat(), address);
    }
    //删除所有标记阵列中消除对它们的引用
    function clearOverlays(infowindow) {
        if(markersArray && markersArray.length > 0) {
            for(var i = 0; i < markersArray.length; i++) {
                markersArray[i].setMap(null);
            }
            markersArray.length = 0;
        }
        if(infowindow) {
            infowindow.close();
        }
    }

    function setiInit() {
        // 页面加载显示默认lng lat address---begin
        if(lattxt != '' && lngtxt != '' && addresstxt != '') {
            var latlng = new google.maps.LatLng(lattxt, lngtxt);
            marker = new google.maps.Marker({
                position: latlng,
                map: map
            });
            markersArray.push(marker);
            attachSecretMessage(marker, latlng, addresstxt);
        }
    }

    function mapClick(lng, lat, address) {
        window.parent.document.getElementById("address_lng").value = lng;
        window.parent.document.getElementById("address_lat").value = lat;
        window.parent.document.getElementById("address").value = address;
    }
    window.onload = function() {
        setiInit();
    }


</script>
<script src="https://maps.googleapis.com/maps/api/js?key=key&libraries=places&callback=initAutocomplete" async defer></script>

1、地理位置请求接口:

地址:https://developers.google.com/maps/documentation/geolocation/intro

地理定位请求使用POST发送到以下URL:https://www.googleapis.com/geolocation/v1/geolocate?key=YOUR_API_KEY

 

根据输入的地址获取经纬度信息:

https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=YOUR_API_KEY

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值