Google map 搜索+点击地图添加标注点 并且返回坐标

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Places Searchbox</title>
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      .controls {
        margin-top: 10px;
        border: 1px solid transparent;
        border-radius: 2px 0 0 2px;
        box-sizing: border-box;
        -moz-box-sizing: border-box;
        height: 32px;
        outline: none;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
      }

      #pac-input {
        background-color: #fff;
        font-family: Roboto;
        font-size: 15px;
        font-weight: 300;
        margin-left: 12px;
        padding: 0 11px 0 13px;
        text-overflow: ellipsis;
        width: 300px;
      }

      #pac-input:focus {
        border-color: #4d90fe;
      }

      .pac-container {
        font-family: Roboto;
      }

      #type-selector {
        color: #fff;
        background-color: #4d90fe;
        padding: 5px 11px 0px 11px;
      }

      #type-selector label {
        font-family: Roboto;
        font-size: 13px;
        font-weight: 300;
      }
      #target {
        width: 345px;
      }
    </style>

  </head>
  <body>
    <input id="pac-input" class="controls" type="text" placeholder="Search Box">
    <div id="map" style="width:800px; height:750px"></div>

    <script>
      // This example adds a search box to a map, using the Google Place Autocomplete
      // feature. People can enter geographical searches. The search box will return a
      // pick list containing a mix of places and predicted search terms.

      // This example requires the Places library. Include the libraries=places
      // parameter when you first load the API. For example:
      // <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
        var lngtxt="{$lng}";
        var lattxt="{$lat}";
        var addresstxt="{$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);
        }
        // ---end
    }
    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("s_county").value = address;
        window.parent.document.getElementById("address").value = address;
        window.parent.initMap();
    }
    window.onload = function () {
        setiInit();
    }
    </script>

    <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY&libraries=places&callback=initAutocomplete"
         async defer></script> 
  </body>
</html>
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值