最近参与页面插入谷歌地图API的项目,所以在此分享下个人学习经验,第一次写,请多担待!javascript
首先,讲下公司的需求,在网页进行点击产品列表,渲染对应的地图信息以及对应的详情信息,而且修改谷歌固有标签以及点击标签出现model,展现详细信息以及对应的产品。html
加载谷歌API并插入页面java
<!DOCTYPE html> <html> <head> <style> /* Set the size of the div element that contains the map */ #map { height: 400px; /* The height is 400 pixels */ width: 100%; /* The width is the width of the web page */ } </style> </head> <body> <h3>My Google Maps Demo</h3> <!--The div element for the map --> <div id="map"></div> <script> // Initialize and add the map function initMap() { // The location of Uluru var uluru = {lat: -25.344, lng: 131.036}; // The map, centered at Uluru var map = new google.maps.Map( document.getElementById('map'), {zoom: 4, center: uluru}); // The marker, positioned at Uluru var marker = new google.maps.Marker({position: uluru, map: map}); } </script> <script async defer src="https://maps.googleapis.com/maps/api/js?key=&callback=initMap"> </script> </body> </html>
而且公司须要咱们在地图高度变高时,须要对标签进行统计,正好Google maps api中正好有对这一方面进行设计,就是‘Marker Clustering’ 【标记聚类】git
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js"> </script> <script> var locations = [ {lat: -31.563910, lng: 147.154312}, {lat: -33.718234, lng: 150.363181}, {lat: -33.727111, lng: 150.371124}, {lat: -33.848588, lng: 151.209834}, {lat: -33.851702, lng: 151.216968}, {lat: -34.671264, lng: 150.863657}, {lat: -35.304724, lng: 148.662905}, {lat: -36.817685, lng: 175.699196}, {lat: -36.828611, lng: 175.790222}, {lat: -37.750000, lng: 145.116667}, {lat: -37.759859, lng: 145.128708}, {lat: -37.765015, lng: 145.133858}, ] // 遍历全部坐标点并添加 var markers = locations.map(function(location, i) { return new google.maps.Marker({ position: location, label: labels[i % labels.length] }); }); // 添加聚类标签 imagePath:标签图片样式 var markerCluster = new MarkerClusterer(map, markers, {imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'}); } </script>
若是须要对聚类标签进行样式修改,能够使用:web
map.data.Setstyle(function(){ var magitude = featrue.getProperty('map'); return { icon:getCircle(magitude); } }); function gitCircle(magitude){ var circle = { path:google.maps.Symbolpath.CIRCLE, scale:magnitude, }; return circle; }
gitCircle() 绘制了一个自定义的圆形,而且回调会maps做为自定义标签。json
初始化渲染完地图后,须要对地图的交互动做进行监听api
自我认为常常用到的动做事件:async
添加事件:学习
map.addListener('dbclick',function(){})
标记点添加事件:google
markers.map(function(v){ v.addListener('click',function(){}) })
删除事件:[removeListener]
而且项目中有一需求,须要对详细地址进行转换为经纬度,所以须要采用Google Maps Geocoding API请求接口
将地址信息转换为经纬度:
$.get('https://maps.googleapis.com/maps/api/geocode/json?address='地址信息'&key=YOUR_API_KEY',(data)=>{ latLng = data.results[0].geomety.location })
将经纬度转换为地址信息
$.get('https://maps.googleapis.com/maps/api/geocode/json?latlng=经度,纬度&key=YOUR_API_KEY',=>(data){ inWhere = data.plus_code.compound_code })
以上是我在一个小项目中主要参考的google maps API 以及 Google Maps Geocoding API 的地方
具体文档:
google maps API