1

I am using the Geolocation Marker Script from the Google Maps Utilities Library V3 in order to display the position of a user.

What I want to achieve (I am a newbie to the Google Maps API!) is:

  • have the users current coordinates displayed (e.g. in a simple CSS container somewhere on the page)

  • connect an event to a marker. I should be triggered when the user is close.

Appreciate your help!

4

1 回答 1

0

To display coordinates to the user, you would need a reference to a DOM Element. Then it's a simple matter of updating the content.

HTML On the Page

<div id="UserCoordinates">Waiting on GPS Position ...</div>

In Script

google.maps.event.addListener(GeoMarker, 'position_changed', function() {
  var UserPosition = this.getPosition();
  var DisplayElement = document.getElementById('UserCoordinates');
  if(UserPosition === null) {
    DisplayElement.innerHTML = 'Waiting on GPS Position...';
  } else {
    DisplayElement.innerHTML =
        'Current Position: ' + UserPosition.toUrlValue();
  }
});

This will show the user their current position as it changes. If you are going to continue using a full screen map, you'll probably want to implement the UserCoordinates div as a map control. The API Reference has a good overview and multiple examples on this.

Display an info window when the user is within X meters of a location

This is a little tricky because there are multiple scenarios to handle and you don't want the infowindow opening repeatedly as they move within your radius.

Distance calculation

I see you have a distance function in your code, but I recommend using the one in the Spherical Geometry library of the API. You just have to specifically load the library with your api script tag:

<script type="text/javascript"
  src="https://maps.googleapis.com/maps/api/js?libraries=geometry&sensor=true_or_false">
</script>

Then you need to add to the position_changed event handler:

var IsWithinRadius = false; //assume they start outside of the circle
var RadiusInMeters = 1000; //within 1 km
var LocationOfInterest = map.getCenter();
google.maps.event.addListener(GeoMarker, 'position_changed', function() {
  var UserPosition = this.getPosition();
  var DisplayElement = document.getElementById('UserCoordinates');
  if(UserPosition === null) {
    DisplayElement.innerHTML = 'Waiting on GPS Position...';
    IsWithinRadius = false; //you don't know where they are
  } else {
    DisplayElement.innerHTML =
        'Current Position: ' + UserPosition.toUrlValue();
    var IsCurrentPositionInRadius =
        Math.abs(google.maps.geometry.spherical.computeDistanceBetween(
            UserPosition, LocationOfInterest)) <= RadiusInMeters;
    var JustEnteredRadius = !IsWithinRadius && IsCurrentPositionInRadius;
    IsWithinRadius = IsCurrentPositionInRadius;
    if(JustEnteredRadius) {
      //trigger action here.
      alert("Within raidus");
    }
  }
});
于 2013-10-31T15:33:02.987 回答