In the next example, called ch08_points, we create some random geocaches based on the user's location. As server-side scripting and client-server connections are also out of the scope of this book, we make our application viable by adding random points within 500 meters of our position. Firstly, we create an empty layer for the points and initialize Geolocation:
var geoloc = new ol.Geolocation({
projection: map.getView().getProjection(),
tracking: true
});
var geoCaching = new ol.layer.Vector({
source: new ol.source.Vector()
});
map.addLayer(geoCaching);The ol.Geolocation constructor creates a simple wrapper object around the HTML5 Geolocation API. It is capable of everything the Geolocation API can do, and provides convenience methods to register listeners on changes and access Geolocation-related information. As we need our position to generate local points, we must register a listener to the Geolocation object's change:position event. As we do not want our application to generate new points on every change, we do this only once:
geoloc.once('change:position', function (evt) {
var altitude = this.getAltitude() || 100;
var myPos = this.getPosition();
map.getView().setCenter(myPos);
map.getView().setZoom(17);
for (var i = 0; i < 50; i += 1) {
geoCaching.getSource().addFeature(new ol.Feature({
geometry: new ol.geom.Point([myPos[0] - 500 + Math.random() * 1000, myPos[1] - 500 + Math.random() * 1000, altitude - 150 + Math.random() * 300]),
loot: 'Treasures of the Seven Seas'
}));
}
});Firstly, we read out all useful information from the Geolocation object. Altitude information will only be present if we have a GPS in our device and proper satellite coverage. Therefore, we default our altitude to a predefined value if we cannot extract it from the object.
Next, we center the map to the measured position, zoom in, and generate 50 random points. As we want to generate points within a 500 meter radius of our location, we calculate a position from a 1000 meter range with a random number. We also calculate a random altitude for every point within the 150 meters from the measured or the predefined altitude value. Finally, we provide a loot attribute just for fun.
If you save and load the example, you will see a map to the one in the following screenshot. You will get the generated geocaches in your area. Just make sure that the application can access your location:
