谷歌地图 API 开发之获取坐标以及街道详情

本身的项目中有获取当前点击的坐标经纬度或者获取当前街道的信息的需求。
估计这个对于新手来讲,仍是比较麻烦的,由于从官网上找这个也并非很好找,要找很久的,运气好的可能会一会儿找到。html

献上本身写的测试案例。代码以下:jquery

<!DOCTYPE html>
<html>

<head>
    <title>Simple Map</title>
    <meta name="viewport" content="initial-scale=1.0">
    <meta charset="utf-8">
    <style> html, body { height: 100%; margin: 0; padding: 0; } #map { height: 100%; } </style>
</head>

<body>
    <div id="map"></div>
    <script>
        function initMap() { var myLatlng = { lat: 39.921323, lng: 116.426239 }; var marker ; var markersArray = []; var map = new google.maps.Map(document.getElementById('map'), { zoom: 12, center: myLatlng }); // ---- Google隐藏 ----
            var isFirstLoad=true; //地图瓦片加载完成以后的回调
            google.maps.event.addListener(map, 'tilesloaded', function () { if (isFirstLoad) { hideLogo(); isFirstLoad=false; } }); function hideLogo() { $("#map .gm-style-cc").hide(); $("#map [title='点击以在 Google 地图上查看此区域']").hide(); } // ---- Google隐藏 ----
            map.addListener('click', function(e) { addMarker(e.latLng, map); //根据经纬度获取 当前地理信息
                var latLngData = e.latLng.lat().toFixed(6)+','+e.latLng.lng().toFixed(6); console.log(latLngData) $.ajax({ type:"post", url:"https://maps.googleapis.com/maps/api/geocode/json?latlng="+latLngData+"&location_type=ROOFTOP&result_type=street_address&key=AIzaSyC8IXpNgfA7uD-Xb0jEqhkEdB7j3gbgOiE", async:true, success:function(data){ console.log(data) var site = latLngData+'<br />'+data.results[0].formatted_address; console.log(site) var infowindow = new google.maps.InfoWindow({ content: site }); infowindow.open(map,marker); //弹出信息提示窗口
 } }); }); //添加坐标对象
            function addMarker(latLng, map) { if(markersArray.length>0){ markersArray[0].setMap(null); }; markersArray.shift(marker) marker = new google.maps.Marker({ position: latLng, map: map }); markersArray.push(marker); } } </script>
    <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC8IXpNgfA7uD-Xb0jEqhkEdB7j3gbgOiE&callback=initMap" async defer></script>
</body>

</html>
<script> $(window).load(function(){ //$("#map [title='点击以在 Google 地图上查看此区域']").hide(); 
        //$('.gm-style-cc').hide();
 }); </script>

注意:请引入本身本地的jquery,由于要用的ajax请求,谷歌的地理服务接口。ajax

代码的核心就在于请求的URL:json

url:"https://maps.googleapis.com/maps/api/geocode/json?latlng="+latLngData+"&location_type=ROOFTOP&result_type=street_address&key=AIzaSyC8IXpNgfA7uD-Xb0jEqhkEdB7j3gbgOiE"

这个是经纬度反向地理编码, 这段url里有四个参数:latlnglocation_typeresult_typekey,具体概念以及参数详解,请参考下一章的 谷歌地图API 开发 之 Geocoding APIsegmentfault

相关文章
相关标签/搜索