How to write a conditional to detect pegman location and create popup box in GoogleMaps?

僤鯓⒐⒋嵵緔 提交于 2020-01-06 20:16:16

问题


I'm working on a simple game in HTML and JavaScript using the GoogleMaps API. The code I have as of now displays the map view on the left side of the screen and street view on the right side of the screen. As you move the arrow keys around, the pegman (that's the little guy that moves around the streets in GoogleMaps) rotates and moves forward and back according to the key pressed (this is a default GoogleMaps feature). The gist of the game is that once the pegman reaches "Point B", you've completed the level and will see a box displaying "Success! Level # complete" or something like that. I'm having trouble writing code to detect that the pegman has arrived in a particular location. (I've been trying to find latLng equals or approximately equals, with no success.) How can my game detect whether a player has approximately reached a given destination. The HTML and JavaScript code below runs the program without any checks for whether the pegman has arrived at Point B.

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
  <title>A2B</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
        <link rel="stylesheet" href="A2B.css"></link>
        <script type="text/javascript" src="pegman_lines.js"></script>
</head>
<body>

<nav class="navbar navbar-default">
  <div class="container">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span> 
      </button>
      <a class="navbar-brand" href="A2B.html">Home</a>
    </div>
    <div class="collapse navbar-collapse" id="myNavbar">
      <ul class="nav navbar-nav navbar-right">
        <li><a href="#">Game</a></li>
        <li><a href="about_game.html">About the game</a></li>
        <li><a href="about_us.html">Developers</a></li>
      </ul>
    </div>
  </div>


</nav>

<div id="map"></div>
<div id="pano"></div>
    <script async defer src="https://maps.googleapis.com/maps/api/js?key=YOURAPICODE&callback=initMap"> 
    </script>
    <script>
    $(document).ready(function () {
            $('#myModal').modal('show');
        });
    </script>
    <div class="container">

  <!-- Modal -->
  <div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">

      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">A to B</h4>
        </div>
        <div class="modal-body">
          <p>
          <b>How to Play:</b><br>
          1. Click on the panorama view <br>
          2. Navigate with arrow keys <br>
          3. Find the fastest way from Point A to Point B!
          </p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Ready!</button>
        </div>
      </div>

    </div>
  </div>

</div>



</div>



<!--<footer class="container-fluid bg-4 text-center">
  <p>Bootstrap Theme Made By <a href="http://www.w3schools.com">www.w3schools.com</a></p> 
</footer>-->

</body>
</html>

JavaScript:

var poly;
var map;
var pointA;
var pointB;

function initMap() {
    var mapDiv = document.getElementById('map');
    map = new google.maps.Map(mapDiv, {
      center: {
        lat: 30.565244,
        lng: -97.671010
      },
      zoom: 14
    });

    var txstate = {
      lat: 30.569858,
      lng: -97.655918
    };
    var panorama = new google.maps.StreetViewPanorama(
      document.getElementById('pano'), {
        position: txstate,
        pov: {
          heading: 34,
          pitch: 10
        }
      });
    google.maps.event.addListener(panorama, 'pano_changed', function() {
      addLatLng({
        latLng: panorama.getPosition()
      });
      if (!map.getBounds().contains(panorama.getPosition())) {
        map.setCenter(panorama.getPosition());
      }
    })
    map.setStreetView(panorama);

    poly = new google.maps.Polyline({
      strokeColor: '#000000',
      strokeOpacity: 1.0,
      strokeWeight: 3
    });
    poly.setMap(map);

    // Add a listener for the click event
    map.addListener('position_change', addLatLng);
  }
  // Handles click events on a map, and adds a new point to the Polyline.

function addLatLng(event) {
  var path = poly.getPath();

  // Because path is an MVCArray, we can simply append a new coordinate
  // and it will automatically appear.
  path.push(event.latLng);

  //point A
  //hard-coded as Texas State University right now
  var image = "https://upload.wikimedia.org/wikipedia/commons/7/73/Farm-Fresh_star.png"; //STAR
  if (!pointA) {
    pointA = new google.maps.Marker({
      position: {
        lat: 30.567989,
        lng: -97.655153
      },
      map: map,
      title: 'tx state',
      label: 'A',
     // animation: google.maps.Animation.DROP
    });
    var contentString_A = '<h5>texas state university at round rock</h5>';
    var infowindow_A = new google.maps.InfoWindow({
      content: contentString_A
    });
    pointA.addListener('click', info_A);

  }

  function info_A() {
    infowindow_A.open(map, pointA);
  }

  //point B
  //hard-coded as H-E-B right now
  if (!pointB) {
    var pointB = new google.maps.Marker({
      position: {
        lat: 30.560619,
        lng: -97.688338
      },
      map: map,
      title: 'heb',
      label: 'B',
      //animation: google.maps.Animation.DROP
    });
    var contentString_B = '<h5>h-e-b</h5>';
    var infowindow_B = new google.maps.InfoWindow({
      content: contentString_B
    });
    pointB.addListener('click', info_B);
  }

  function info_B() {
    infowindow_B.open(map, pointB);
  }

  function toggleBounce() {
    if (marker.getAnimation() !== null) {
      marker.setAnimation(null);
    } else {
      marker.setAnimation(google.maps.Animation.BOUNCE);
    }
  }

}
google.maps.event.addDomListener(window, "load", initMap);

回答1:


The simplest way is to use the google.maps.geometry.spherical.computeDistanceBetween method. Set an arbitrary distance (1 meter is what I commonly use, but you might want to increase the tolerance (distance) to make it easier to be "there"). Looking at your existing code, pointA is over 100 meters from anywhere near a StreetView panorama (a 120 meter threshold works), while pointB seems to be pretty close to one (looks like 15 meters will work, but I didn't test that one).

proof of concept fiddle

code snippet:

var poly;
var map;
var pointA;
var pointB;
var infowindow_A;
var infowindow_B;

function initMap() {
    var mapDiv = document.getElementById('map');
    map = new google.maps.Map(mapDiv, {
      center: {
        lat: 30.565244,
        lng: -97.671010
      },
      zoom: 14
    });
    var svLayer = new google.maps.StreetViewCoverageLayer();
    svLayer.setMap(map);
    var txstate = {
      lat: 30.569858,
      lng: -97.655918
    };
    var panorama = new google.maps.StreetViewPanorama(
      document.getElementById('pano'), {
        position: txstate,
        pov: {
          heading: 34,
          pitch: 10
        }
      });
    google.maps.event.addListener(panorama, 'pano_changed', function() {
      addLatLng({
        latLng: panorama.getPosition()
      });
      if (!map.getBounds().contains(panorama.getPosition())) {
        map.setCenter(panorama.getPosition());
      }
    })
    map.setStreetView(panorama);

    poly = new google.maps.Polyline({
      strokeColor: '#000000',
      strokeOpacity: 1.0,
      strokeWeight: 3
    });
    poly.setMap(map);

    // Add a listener for the click event
    map.addListener('position_change', addLatLng);
  }
  // Handles click events on a map, and adds a new point to the Polyline.

function addLatLng(event) {
  var path = poly.getPath();

  // Because path is an MVCArray, we can simply append a new coordinate
  // and it will automatically appear.
  path.push(event.latLng);

  //point A
  //hard-coded as Texas State University right now
  var image = "https://upload.wikimedia.org/wikipedia/commons/7/73/Farm-Fresh_star.png"; //STAR
  if (!pointA) {
    pointA = new google.maps.Marker({
      position: {
        lat: 30.567989,
        lng: -97.655153
      },
      map: map,
      title: 'tx state',
      label: 'A',
      // animation: google.maps.Animation.DROP
    });
    var circle = new google.maps.Circle({
      map: map,
      radius: 120,
      center: pointA.getPosition()
    });
    var contentString_A = '<h5>texas state university at round rock</h5>';
    infowindow_A = new google.maps.InfoWindow({
      content: contentString_A
    });
    pointA.addListener('click', info_A);

  }

  function info_A() {
    infowindow_A.open(map, pointA);
  }

  //point B
  //hard-coded as H-E-B right now
  if (!pointB) {
    var pointB = new google.maps.Marker({
      position: {
        lat: 30.560619,
        lng: -97.688338
      },
      map: map,
      title: 'heb',
      label: 'B',
      //animation: google.maps.Animation.DROP
    });
    var circleB = new google.maps.Circle({
      map: map,
      radius: 15,
      center: pointB.getPosition()
    });

    var contentString_B = '<h5>h-e-b</h5>';
    infowindow_B = new google.maps.InfoWindow({
      content: contentString_B
    });
    pointB.addListener('click', info_B);
  }
  if (google.maps.geometry.spherical.computeDistanceBetween(pointB.getPosition(), event.latLng) < 15) {
    infowindow_B.open(map, pointB);
  } else if (google.maps.geometry.spherical.computeDistanceBetween(pointA.getPosition(), event.latLng) < 120) {
    infowindow_A.open(map, pointA);
  }


  function info_B() {
    infowindow_B.open(map, pointB);
  }

  function toggleBounce() {
    if (marker.getAnimation() !== null) {
      marker.setAnimation(null);
    } else {
      marker.setAnimation(google.maps.Animation.BOUNCE);
    }
  }

}
google.maps.event.addDomListener(window, "load", initMap);
html,
body {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
#map {
  height: 100%;
  width: 45%;
  float: left;
  margin: 0px;
  padding: 0px
}
#pano {
  height: 100%;
  width: 45%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
<nav class="navbar navbar-default">
  <div class="container">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="A2B.html">Home</a>
    </div>
    <div class="collapse navbar-collapse" id="myNavbar">
      <ul class="nav navbar-nav navbar-right">
        <li><a href="#">Game</a>
        </li>
        <li><a href="about_game.html">About the game</a>
        </li>
        <li><a href="about_us.html">Developers</a>
        </li>
      </ul>
    </div>
  </div>


</nav>

<div id="map"></div>
<div id="pano"></div>


来源:https://stackoverflow.com/questions/38776046/how-to-write-a-conditional-to-detect-pegman-location-and-create-popup-box-in-goo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!