将信息窗口添加到方向图

时间:2018-01-03 23:20:00

标签: javascript google-maps google-maps-api-3

我正在使用https://www.sitepoint.com/find-a-route-using-the-geolocation-and-the-google-maps-api/中的代码构建一个从用户位置到多个足球场选项的旅行计划器。

我已经成功使用下面的代码,但我想添加另一个元素。我想将信息窗口添加到目标标记(点击打开),其中包含体育场名称和描述。

我尝试添加此处的代码https://developers.google.com/maps/documentation/javascript/infowindows

......但它不起作用。

有人可以帮忙吗?

这是我的代码:)

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Find a route using Geolocation and Google Maps API</title>
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>


<script>
  function calculateRoute(from, to) {
    // Center initialized somewhere near London
    var myOptions = {
      zoom: 10,
      center: new google.maps.LatLng(53, -1),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    // Draw the map
    var mapObject = new google.maps.Map(document.getElementById("map"), myOptions);

    var directionsService = new google.maps.DirectionsService();
    var directionsRequest = {
      origin: from,
      destination: to,
      travelMode: google.maps.DirectionsTravelMode.TRANSIT,
      unitSystem: google.maps.UnitSystem.METRIC
    };
    directionsService.route(
      directionsRequest,
      function(response, status)
      {
        if (status == google.maps.DirectionsStatus.OK)
        {
          new google.maps.DirectionsRenderer({
            map: mapObject,
            directions: response
          });
        }
        else
          $("#error").append("Unable to retrieve your route<br />");
      }
    );
  }

  $(document).ready(function() {
    // If the browser supports the Geolocation API
    if (typeof navigator.geolocation == "undefined") {
      $("#error").text("Your browser doesn't support the Geolocation API");
      return;
    }

    $("#from-link, #to-link").click(function(event) {
      event.preventDefault();
      var addressId = this.id.substring(0, this.id.indexOf("-"));

      navigator.geolocation.getCurrentPosition(function(position) {
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode({
          "location": new google.maps.LatLng(position.coords.latitude, position.coords.longitude)
        },
        function(results, status) {
          if (status == google.maps.GeocoderStatus.OK)
            $("#" + addressId).val(results[0].formatted_address);
          else
            $("#error").append("Unable to retrieve your address<br />");
        });
      },


      function(positionError){
        $("#error").append("Error: " + positionError.message + "<br />");
      },
      {
        enableHighAccuracy: true,
        timeout: 10 * 1000 // 10 seconds
      });
    });

    $("#calculate-route").submit(function(event) {
      event.preventDefault();
      calculateRoute($("#from").val(), $("#to").val());
    });


  });
</script>
<style type="text/css">
  #map {
    width: 500px;
    height: 400px;
    margin-top: 10px;
  }
</style>
  </head>
  <body>
<h1>Calculate your route</h1>
<form id="calculate-route" name="calculate-route" action="#" method="get">
  <label for="from">From:</label>
  <input type="text" id="from" name="from" required="required" placeholder="An address" size="30" />
  <a id="from-link" href="#">Get my position</a>
  <br />

  <label for="to">To:</label>
  <select id="to">
    <option value="51.5548885,-0.108438">Arsenal's Emirates Stadium</option>
    <option value="51.481663,-0.1931505">Chelsea's Stamford Bridge</option>
  </select>

  <br />

  <input type="submit" />
  <input type="reset" />
</form>
<div id="map"></div>
<p id="error"></p>

1 个答案:

答案 0 :(得分:1)

  1. suppressMarkers:true上使用DirectionsRenderer删除原始标记。
  2. new google.maps.DirectionsRenderer({
      map: mapObject,
      directions: response,
      suppressMarkers: true
    });
    
    1. 添加createMarker功能以创建新标记(来自类似问题:How to give static message in google map API
    2. function createMarker(latlng, title, html, color, label, map) {
        var contentString = '<b>' + title + '</b><br>' + html;
        var marker = new google.maps.Marker({
          position: latlng,
          draggable: true,
          map: map,
          icon: getMarkerImage(color),
          shape: iconShape,
          title: title,
          label: label,
          zIndex: Math.round(latlng.lat() * -100000) << 5
        });
        marker.myname = title;
      
        google.maps.event.addListener(marker, 'click', function() {
          infowindow.setContent(contentString);
          infowindow.open(map, marker);
        });
      
        return marker;
      }
      

      proof of concept fiddle

      screen shot of resulting map

      代码段

      function calculateRoute(from, to) {
        // Center initialized somewhere near London
        var myOptions = {
          zoom: 10,
          center: new google.maps.LatLng(53, -1),
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        // Draw the map
        var mapObject = new google.maps.Map(document.getElementById("map"), myOptions);
      
        var directionsService = new google.maps.DirectionsService();
        var directionsRequest = {
          origin: from,
          destination: to,
          travelMode: google.maps.DirectionsTravelMode.TRANSIT,
          unitSystem: google.maps.UnitSystem.METRIC
        };
        directionsService.route(
          directionsRequest,
          function(response, status) {
            if (status == google.maps.DirectionsStatus.OK) {
              new google.maps.DirectionsRenderer({
                map: mapObject,
                directions: response,
                suppressMarkers: true
              });
              console.log(response.routes.length);
              createMarker(response.routes[0].legs[0].start_location, "start", document.getElementById('from').value, "green", "A", mapObject);
              createMarker(response.routes[0].legs[0].end_location, "end", $("#to option:selected").text(), "red", "B", mapObject)
            } else
              $("#error").append("Unable to retrieve your route<br />");
          }
        );
      }
      
      $(document).ready(function() {
        // If the browser supports the Geolocation API
        if (typeof navigator.geolocation == "undefined") {
          $("#error").text("Your browser doesn't support the Geolocation API");
          return;
        }
      
        $("#from-link, #to-link").click(function(event) {
          event.preventDefault();
          var addressId = this.id.substring(0, this.id.indexOf("-"));
      
          navigator.geolocation.getCurrentPosition(function(position) {
              var geocoder = new google.maps.Geocoder();
              geocoder.geocode({
                  "location": new google.maps.LatLng(position.coords.latitude, position.coords.longitude)
                },
                function(results, status) {
                  if (status == google.maps.GeocoderStatus.OK)
                    $("#" + addressId).val(results[0].formatted_address);
                  else
                    $("#error").append("Unable to retrieve your address<br />");
                });
            },
      
      
            function(positionError) {
              $("#error").append("Error: " + positionError.message + "<br />");
            }, {
              enableHighAccuracy: true,
              timeout: 10 * 1000 // 10 seconds
            });
        });
      
        $("#calculate-route").submit(function(event) {
          event.preventDefault();
          calculateRoute($("#from").val(), $("#to").val());
        });
      });
      var icons = new Array();
      icons["red"] = {
        url: "http://maps.google.com/mapfiles/ms/micons/red.png",
        // This marker is 32 pixels wide by 32 pixels tall.
        size: new google.maps.Size(32, 32),
        // The origin for this image is 0,0.
        origin: new google.maps.Point(0, 0),
        // The anchor for this image is at 9,34.
        anchor: new google.maps.Point(16, 32),
        labelOrigin: new google.maps.Point(16, 10)
      };
      
      function getMarkerImage(iconColor) {
        if ((typeof(iconColor) == "undefined") || (iconColor == null)) {
          iconColor = "red";
        }
        if (!icons[iconColor]) {
          icons[iconColor] = {
            url: "http://maps.google.com/mapfiles/ms/micons/" + iconColor + ".png",
            // This marker is 32 pixels wide by 32 pixels tall.
            size: new google.maps.Size(32, 32),
            // The origin for this image is 0,0.
            origin: new google.maps.Point(0, 0),
            // The anchor for this image is at 6,20.
            anchor: new google.maps.Point(16, 32),
            labelOrigin: new google.maps.Point(16, 10)
          };
        }
        return icons[iconColor];
      
      }
      // Marker sizes are expressed as a Size of X,Y
      // where the origin of the image (0,0) is located
      // in the top left of the image.
      
      // Origins, anchor positions and coordinates of the marker
      // increase in the X direction to the right and in
      // the Y direction down.
      
      var iconImage = {
        url: 'http://maps.google.com/mapfiles/ms/micons/red.png',
        // This marker is 20 pixels wide by 34 pixels tall.
        size: new google.maps.Size(20, 34),
        // The origin for this image is 0,0.
        origin: new google.maps.Point(0, 0),
        // The anchor for this image is at 9,34.
        anchor: new google.maps.Point(9, 34)
      };
      // Shapes define the clickable region of the icon.
      // The type defines an HTML &lt;area&gt; element 'poly' which
      // traces out a polygon as a series of X,Y points. The final
      // coordinate closes the poly by connecting to the first
      // coordinate.
      var iconShape = {
        coord: [9, 0, 6, 1, 4, 2, 2, 4, 0, 8, 0, 12, 1, 14, 2, 16, 5, 19, 7, 23, 8, 26, 9, 30, 9, 34, 11, 34, 11, 30, 12, 26, 13, 24, 14, 21, 16, 18, 18, 16, 20, 12, 20, 8, 18, 4, 16, 2, 15, 1, 13, 0],
        type: 'poly'
      };
      var infowindow = new google.maps.InfoWindow({
        size: new google.maps.Size(150, 50)
      });
      
      function createMarker(latlng, title, html, color, label, map) {
        var contentString = '<b>' + title + '</b><br>' + html;
        var marker = new google.maps.Marker({
          position: latlng,
          draggable: true,
          map: map,
          icon: getMarkerImage(color),
          shape: iconShape,
          title: title,
          label: label,
          zIndex: Math.round(latlng.lat() * -100000) << 5
        });
        marker.myname = title;
        // gmarkers.push(marker);
      
        google.maps.event.addListener(marker, 'click', function() {
          infowindow.setContent(contentString);
          infowindow.open(map, marker);
        });
      
        return marker;
      }
      html,
      body,
      #map {
        height: 100%;
        width: 100%;
        margin: 0px;
        padding: 0px;
        background-color: white;
      }
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <script src="https://maps.googleapis.com/maps/api/js"></script>
      <h1>Calculate your route</h1>
      <form id="calculate-route" name="calculate-route" action="#" method="get">
        <label for="from">From:</label>
        <input type="text" id="from" name="from" required="required" placeholder="An address" size="30" value="Croydon, UK" />
        <a id="from-link" href="#">Get my position</a>
        <br />
      
        <label for="to">To:</label>
        <select id="to">
          <option value="51.5548885,-0.108438">Arsenal's Emirates Stadium</option>
          <option value="51.481663,-0.1931505">Chelsea's Stamford Bridge</option>
        </select>
      
        <br />
      
        <input type="submit" />
        <input type="reset" />
      </form>
      <div id="map"></div>
      <p id="error"></p>