简体   繁体   English

如何将自定义地图标记与Google Map的自动完成搜索框结合在一起?

[英]How do I combine customized map markers with Google Map's autocomplete search box?

I have managed to create code that displays customized, clickable markers on Google Maps. 我设法创建了在Google地图上显示自定义可点击标记的代码。 I also have a separate interface that searches locations from Google Maps' database using Autocomplete. 我还有一个单独的界面,可使用自动完成功能从Google Maps数据库中搜索位置。 I'm having trouble combining these two. 我在将两者结合时遇到了麻烦。

Here is the code for the one with the search box (w/o my API Key): 这是带有搜索框的代码(不带我的API密钥):

<!DOCTYPE html>
<html>
<head>
    <title>Hoshizora Map</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <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;
      }
      #description {
        font-family: Roboto;
        font-size: 15px;
        font-weight: 300;
      }
      #infowindow-content .title {
        font-weight: bold;
      }
      #infowindow-content {
        display: none;
      }
      #map #infowindow-content {
        display: inline;
      }
      .pac-card {
        margin: 10px 10px 0 0;
        border-radius: 2px 0 0 2px;
        box-sizing: border-box;
        -moz-box-sizing: border-box;
        outline: none;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
        background-color: #fff;
        font-family: Roboto;
      }
      #pac-container {
        padding-bottom: 12px;
        margin-right: 12px;
      }
      .pac-controls {
        display: inline-block;
        padding: 5px 11px;
      }
      .pac-controls label {
        font-family: Roboto;
        font-size: 13px;
        font-weight: 300;
      }
      #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: 400px;
      }
      #pac-input:focus {
        border-color: #4d90fe;
      }
      #title {
        color: #fff;
        background-color: #4d90fe;
        font-size: 25px;
        font-weight: 500;
        padding: 6px 12px;
      }
      #target {
        width: 345px;
      }
    </style>
  </head>
  <body>
    <h2>Schools of Current Adik Bintang in DIY</h2>
    <!--Card Information Division-->
    <div class="pac-card" id="pac-card">
      <div>
        <div id="title">
          Lokasi Adik Bintang
        </div>
      </div>
      <div id="pac-container">
        <input id="pac-input" type="text"
            placeholder="Enter an Adik Bintang">
      </div>
    </div>
    <div id="map"></div>
    <!--Popup Information Card Division-->
    <div id="infowindow-content">
      <img src="" width="16" height="16" id="place-icon">
      <span id="place-name"  class="title"></span><br>
      <span id="place-address"></span>
    </div>

  <script>
      //Map Interface
      var map;
      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          center: {lat:-7.88806,lng:110.32889},
          zoom: 12
        });

        //defines card to
        var card = document.getElementById('pac-card');
        //corners the box (card)
        map.controls[google.maps.ControlPosition.TOP_RIGHT].push(card);

        //defines input for AutoComplete
        var input = document.getElementById('pac-input');
        //software for Autocomplete
        var autocomplete = new google.maps.places.Autocomplete(input);

        //Zooms into the area searched
        autocomplete.bindTo('bounds', map);
        //completes the search and defines/pulls out info window
        var infowindow = new google.maps.InfoWindow();
        //info window content
        var infowindowContent = document.getElementById('infowindow-content');
        infowindow.setContent(infowindowContent);
        function addMarker(props){}
        var marker = new google.maps.Marker({
          //puts the window properly
          map: map,
          //how far the window is with the marker
          anchorPoint: new google.maps.Point(0, -29)
        });


        autocomplete.addListener('place_changed', function() {
          //idk with these two do
          infowindow.close();
          marker.setVisible(true);
          //Makes it Happen
          var place = autocomplete.getPlace();
          if (!place.geometry) {
            // User entered the name of a Place that was not suggested and pressed the Enter key, or the Place Details request failed.
            window.alert("No details available for input: '" + place.name + "'");
            return;
          }

          // If the place has a geometry, then present it on a map.
          if (place.geometry.viewport) {
            map.fitBounds(place.geometry.viewport);
          } else {
            map.setCenter(place.geometry.location);
            map.setZoom(17);
          }
          marker.setPosition(place.geometry.location);
          //idk
          marker.setVisible(true);

        //shows the infobox
          var address = '';
          if (place.address_components) {
            address = [
              //infobox formula
              (place.address_components[0] && place.address_components[0].short_name || ''),
              (place.address_components[1] && place.address_components[1].short_name || ''),
              (place.address_components[2] && place.address_components[2].short_name || '')
            ].join(' ');
          }

          //Content
          infowindowContent.children['place-icon'].src = place.icon;
          infowindowContent.children['place-name'].textContent = place.name;
          infowindowContent.children['place-address'].textContent = address;
          //shows the window
          infowindow.open(map, marker);
        });

        document.getElementById('use-strict-bounds')
            .addEventListener('click', function() {
              console.log('Checkbox clicked! New state=' + this.checked);
              autocomplete.setOptions({strictBounds: this.checked});
            });
      }
    </script>

<script src="https://maps.googleapis.com/maps/api/js?key=[APIKEY]&libraries=places&callback=initMap"
        async defer></script>
  </body>
</html>

Here is the code for the map with one customized marker(w/o my API Key): 这是带有一个自定义标记(不带我的API密钥)的地图代码:

<!DOCTYPE html>
<html>
  <head>
    <title>Hoshizora Map</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <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;
      }
      #description {
        font-family: Roboto;
        font-size: 15px;
        font-weight: 300;
      }
      #infowindow-content .title {
        font-weight: bold;
      }
      #infowindow-content {
        display: none;
      }
      #map #infowindow-content {
        display: inline;
      }
      .pac-card {
        margin: 10px 10px 0 0;
        border-radius: 2px 0 0 2px;
        box-sizing: border-box;
        -moz-box-sizing: border-box;
        outline: none;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
        background-color: #fff;
        font-family: Roboto;
      }
      #pac-container {
        padding-bottom: 12px;
        margin-right: 12px;
      }
      .pac-controls {
        display: inline-block;
        padding: 5px 11px;
      }
      .pac-controls label {
        font-family: Roboto;
        font-size: 13px;
        font-weight: 300;
      }
      #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: 400px;
      }
      #pac-input:focus {
        border-color: #4d90fe;
      }
      #title {
        color: #fff;
        background-color: #4d90fe;
        font-size: 25px;
        font-weight: 500;
        padding: 6px 12px;
      }
      #target {
        width: 345px;
      }
    </style>
  </head>
  <body>
    <h1>Schools of Current Adik Bintang in DIY</h1>
    <div id="map"></div>
    <script>
      var map;
      function initMap() {
        //New map options
        map = new google.maps.Map(document.getElementById('map'), {
          center: {lat:-7.88806,lng:110.32889},
          zoom: 12
        });

      //HEC
      addMarker({
        coords:{lat:-7.892623,lng:110.301695},
        iconImage:'HEC.jpg',
        content:'<h3>Hoshizora Educational Center<br>Headquarters</h3><img src = "HEC-BUILDING.jpg"<br><h3><a href="https://www.hoshizora.org/contact/">Contact Us</a></h3>'
      });

      // Add Marker Function
      function addMarker(props){
      var marker = new google.maps.Marker({
        position:props.coords,
        map:map,
        icon:props.iconImage
      });
      // Check for custom icon
      if(props.iconImage){
        // Set icon image
        marker.setIcon(props.iconImage);
      }
      // Check content
      if(props.content){
        var infoWindow = new google.maps.InfoWindow({
          content:props.content
        });

        marker.addListener('click', function(){
          infoWindow.open(map,marker);
        marker.addListener('click', function(){
          infoWindow.close(map,marker);
        marker.addListener('click', function(){
          infoWindow.open(map,marker);
        marker.addListener('click', function(){
          infoWindow.close(map,marker);
        marker.addListener('click', function(){
          infoWindow.open(map,marker);
          })
          })
        })
        })
        });
      }
    }
  }

    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=[APIKEY]&libaries=places&callback=initMap"
    async defer></script>
  </body>
</html>

I would like to somehow combine these two codes to one interface in which I can search locations with the created customized markers visible on the map. 我想以某种方式将这两个代码组合到一个界面中,在其中可以使用在地图上可见的已创建的自定义标记来搜索位置。 Thanks! 谢谢!

Actually, this one is pretty simple. 实际上,这很简单。

I modified your code #1. 我修改了您的代码#1。 I used a sample icon that I manage to get from Google images (please don't use this to avoid copyright issues). 我使用了一个设法从Google图片中获取的示例图标(请不要使用它来避免版权问题)。

I've added an ' icon ' property in your Marker object (here's the documentation for Icon object specification ) . 我已经在Marker对象中添加了一个' icon '属性(这是Icon对象规范的文档 Under the icon's url property, I referenced the path of the icon that I will be using and supplied values to scaledSize property for scaling (use this property to stretch/shrink an image or a sprite). 图标的 url属性下,我引用了将要使用的图标的路径,并将其值提供给scaledSize属性以进行缩放(使用此属性来拉伸/收缩图像或精灵)。

Then in your infowindow, I've created an HTML template in template variable. 然后在您的信息窗口中,我在模板变量中创建了一个HTML模板。 In there, I've placed the thumbnail, address, and the link to your website. 在其中,我放置了缩略图,地址和指向您网站的链接。 I've also added css for that template in the head section. 我还在开头部分为该模板添加了CSS。

Here's the live demo 这是现场演示

The marker: 标记:

var marker = new google.maps.Marker({
  icon : {
      url : 'https://d30y9cdsu7xlg0.cloudfront.net/png/65999-200.png',
      scaledSize : new google.maps.Size(60,60),
  },
  map: map,
  anchorPoint: new google.maps.Point(0, -50)
});

the infowindow content: 信息窗口内容:

var template = '<div class="customInfoWindowContentHolder">'
    template += '<div class="title">'+place.formatted_address+'</div>';
    template += '<div class="thumbnail"><img src="https://d30y9cdsu7xlg0.cloudfront.net/png/65999-200.png"></img></div>';
    template += '<div class="linkBottom"><a href="https://www.hoshizora.org/contact/" >Contact Us</a></div>';
    template += '</div>';

Hope it helps! 希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM