I'm trying to make a Polymer module for working with OpenLayers 3 and displaying openstreetmaps. I know there is a great module working with leaflet but I need some specifics functions like map orientation.
Anyway, I code something and it's working except one thing I can't figure out : When the page loads, only the commands are showing (Zoom + / Zoom -) and not the map (and not any thing such as marker, etc). But if I resize my window (my Chrome window I mean) the map appear and all is working fine !! I was thinking maybe something in relation with DOM Loading...
Module code :
<dom-module id="openlayer-map">
<link rel="stylesheet" href="http://openlayers.org/en/v3.7.0/css/ol.css" type="text/css">
<script src="http://openlayers.org/en/v3.7.0/build/ol.js" type="text/javascript"></script>
<style>
:host {
display: block;
}
#map
{
position: absolute;
height: 100%;
}
</style>
<template>
<div id="map" class="map"></div>
<!-- Tests
<input is="iron-input" bind-value="{{latitude}}" placeholder="latitude">
<input is="iron-input" bind-value="{{longitude}}" placeholder="longitude">
-->
</template>
</dom-module>
<script>
(function() {
Polymer({
is: 'openlayer-map',
properties:
{
currentCenter: Array,
currentView: ol.View,
olmap: ol.Map,
geolocation: ol.Geolocation,
layer: Object,
longitude:
{
type: Number,
value:12.889101100000062,
notify: true,
observer: '_updateLongitude'
},
latitude:
{
type: Number,
value: 15.7622695,
notify: true,
observer: '_updateLatitude'
},
geotracking:
{
value: false,
type: Boolean,
notify: true,
},
elemReady: Boolean,
},
ready: function()
{
console.log('openlayer-map ready');
this.initialConfig();
this.elemReady = true;
this.setCenter(this.latitude,this.longitude);
},
initialConfig: function()
{
console.log('initial config for the map...');
this.currentView = new ol.View({
zoom: 14
});
var source = new ol.source.OSM();
this.layer = new ol.layer.Tile();
this.layer.setSource(source);
this.olmap = new ol.Map({
layers: [this.layer],
target: this.$.map,
controls: ol.control.defaults({
attributionOptions: /** #type {olx.control.AttributionOptions} */ ({
collapsible: false
})
}),
view: this.currentView
});
// Localisation
this.geolocation = new ol.Geolocation({
projection: this.currentView.getProjection()
});
this.geolocation.setTracking(this.geotracking);
if(this.geolocation)
{
var accuracyFeature = new ol.Feature();
this.geolocation.on('change:accuracyGeometry', function() {
accuracyFeature.setGeometry(this.geolocation.getAccuracyGeometry());
}.bind(this));
var positionFeature = new ol.Feature();
positionFeature.setStyle(new ol.style.Style({
image: new ol.style.Circle({
radius: 6,
fill: new ol.style.Fill({
color: '#3399CC'
}),
stroke: new ol.style.Stroke({
color: '#fff',
width: 2
})
})
}));
this.geolocation.on('change:position', function() {
var coordinates = this.geolocation.getPosition();
positionFeature.setGeometry(coordinates ?
new ol.geom.Point(coordinates) : null);
}.bind(this));
var featuresOverlay = new ol.layer.Vector({
map: this.olmap,
source: new ol.source.Vector({
features: [accuracyFeature, positionFeature]
})
});
}
},
_updateLatitude: function(newValue, oldValue)
{
if(this.elemReady)
{
console.log('update latitude from '+oldValue+' to '+newValue);
this.setCenter(newValue, this.longitude);
}
else
{
console.log('_updateLatitude: waiting element to be ready');
}
},
_updateLongitude: function(newValue, oldValue)
{
if(this.elemReady)
{
console.log('update longitude from '+oldValue+' to '+newValue);
this.setCenter(this.latitude, newValue);
}
else
{
console.log('_updateLatitude: waiting element to be ready');
}
},
setCenter: function(latitude, longitude)
{
var center = [longitude, latitude];
this.currentCenter = ol.proj.fromLonLat(center);
console.log('update center of the map with latitude = '+latitude+' and longitude = '+longitude);
this.currentView.centerOn(this.currentCenter,[400,400], [0,0]);
},
});
})();
</script>
And the call in Polymer :
<openlayer-map latitude="48.853" longitude="2.35" geotracking></openlayer-map>
Any clue ?
Found it ! Needed to do the map initialization in an asynchronous call
attached: function()
{
this.async(function()
{
this.initialConfig(); // Create your ol.Map here
});
},
Related
I have a problem in my open layer (6.1.) project with a popup bubble.
I am not able to create and see the popup and fill it, not even with a single GeoJSON layer with cities.
I read this without progress:
popup with multiple points features
I would like just render the name of the city when clicking on the icon.
Index.html
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link rel="icon" href="pic/fav.png" sizes="192x192" />
<link rel="stylesheet" type="text/css" href="style.css">
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<title>Retail Space</title>
</head>
<!--++++++++++++++++++++++++++++++++++++++ BODY +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>
<body>
<div id="container">
<!--++++++++++++++++++++++++++++++++++++++ HEADERBAR +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>
<div id="headerbar">
<div id="logobar">
</div>
<div id="controlbar">
</div>
</div>
<!--++++++++++++++++++++++++++++++++++++++ MAPBAR +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>
<div id="map-container" ><div id="popup"></div>
<div id="tooltip" class="tooltip"></div>
</div>
<script src="main.js"></script>
</div> <!--/container-->
</body>
</html>
main.js
import GeoJSON from 'ol/format/GeoJSON';
import TileJSON from 'ol/source/TileJSON';
import Map from 'ol/Map';
import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';
import View from 'ol/View';
import VectorTileLayer from 'ol/layer/VectorTile';
import VectorTileSource from 'ol/source/VectorTile';
import TileLayer from 'ol/layer/Tile';
import Feature from 'ol/Feature';
import Point from 'ol/geom/Point';
import OSM from 'ol/source/OSM';
import TileWMS from 'ol/source/TileWMS';
import Overlay from 'ol/Overlay';
import {Style, Fill, Stroke, Icon} from 'ol/style';
import {fromLonLat} from 'ol/proj';
import sync from 'ol-hashed';
var iconStyle_municip = new Style({
image: new Icon({
anchor: [0.5, 5],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
src: 'pic/municip.png'
})
});
//OSM layer creation
var OSMmap = new TileLayer({
source: new OSM(),
format: new GeoJSON({featureProjection: 'EPSG:3857'}),
});
//Obce 5000+ layer creation
var cities = new VectorLayer({
source: new VectorSource({
format: new GeoJSON({featureProjection: 'EPSG:3857'}),
url: 'obce5000geojson.geojson'
})
});
cities.setStyle(iconStyle_municip);
//Map initiation
new Map({
target: 'map-container',
layers: [OSMmap, cities],
view: new View({
center: fromLonLat([15, 49.80]),
zoom: 8
}),
});
//tooltip start
var element = document.getElementById('popup');
var popup = new Overlay({
element: element,
positioning: 'bottom-center',
stopEvent: false,
offset: [0, -50]
});
map.addOverlay(popup);
// display popup on click
map.on('click', function(evt) {
var feature = map.forEachFeatureAtPixel(evt.pixel,
function(feature) {
return feature;
}
);
if (feature) {
var coordinates = this.getCoordinateFromPixel(evt.pixel);
popup.setPosition(coordinates);
$(element).popover({
'placement': 'top',
'html': true,
'content': feature.get('obec')
});
$(element).popover('show');
} else {
$(element).popover('destroy');
}
});
Main problem is you aren't retaining a reference to your map variable.
//Map initiation
new Map({
target: 'map-container',
layers: [OSMmap, cities],
view: new View({
center: fromLonLat([15, 49.80]),
zoom: 8
}),
});
That fails when the code tries to use it:
map.addOverlay(popup);
Keep a reference to the map:
//Map initiation
var map = new Map({
target: 'map-container',
layers: [OSMmap, cities],
view: new View({
center: fromLonLat([15, 49.80]),
zoom: 8
}),
});
proof of concept fiddle
code snippet:
var iconStyle_municip = new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 5],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
src: 'https://openlayers.org/en/v4.6.5/examples/data/icon.png'
})
});
//OSM layer creation
var OSMmap = new ol.layer.Tile({ // TileLayer({
source: new ol.source.OSM(),
format: new ol.format.GeoJSON({featureProjection: 'EPSG:3857'}),
});
//Obce 5000+ layer creation
var cities = new ol.layer.Vector({ // VectorLayer({
source: new ol.source.Vector({ // VectorSource({
format: new ol.format.GeoJSON({featureProjection: 'EPSG:3857'}),
url: 'https://api.myjson.com/bins/upiqa'
})
});
cities.setStyle(iconStyle_municip);
//Map initiation
var map = new ol.Map({
target: 'map-container',
layers: [OSMmap, cities],
view: new ol.View({
center: ol.proj.fromLonLat([15, 0]),
zoom: 2
}),
});
//tooltip start
var element = document.getElementById('popup');
var popup = new ol.Overlay({
element: element,
positioning: 'bottom-center',
stopEvent: false,
offset: [0, -10]
});
map.addOverlay(popup);
map.on('click', function(evt) {
var feature = map.forEachFeatureAtPixel(evt.pixel,
function(feature) {
return feature;
}
);
if (feature) {
var coordinates = this.getCoordinateFromPixel(evt.pixel);
popup.setPosition(coordinates);
$(element).popover({
'placement': 'top',
'html': true,
'content': "test content" // feature.get('obec')
});
$(element).popover('show');
} else {
$(element).popover('destroy');
}
});
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map-container {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#popup {
background: #FFFFFF;
border: black 1px solid;
}
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io#master/en/v6.1.1/build/ol.js"></script>
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
<div id="map-container" class="map"></div>
<script src="https://cdn.jsdelivr.net/npm/jquery-popover#0.0.4/src/jquery-popover.min.js"></script>
<div id="popup">
<b>test</b>
</div>
I'm trying to locate the user when the website is fully loaded.
I'm using the newest MapBox API (JavaScript)
Is it possible to do that without requiring the user to click on the top right button on the map?
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v11',
center: [0,0],
zoom: 15 // starting zoom
});
// Add geolocate control to the map.
map.addControl(new mapboxgl.GeolocateControl({
positionOptions: {
enableHighAccuracy: true
},
trackUserLocation: true
}));
try with this example, it's work for me
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title></title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='https://cdnjs.cloudflare.com/ajax/libs/mapbox-gl/0.53.1/mapbox-gl.js'></script>
<link href='https://cdnjs.cloudflare.com/ajax/libs/mapbox-gl/0.53.1/mapbox-gl.css' rel='stylesheet' />
<style>
body { margin:0; padding:0; }
#map { position:absolute; top:0; bottom:0; width:100%; }
</style>
<script >
var get_location = function() {
var geolocation = null;
var c_pos = null;
if (window.navigator && window.navigator.geolocation) {
geolocation = window.navigator.geolocation;
var positionOptions = {
enableHighAccuracy: true,
timeout: 10 * 1000, // 10 seconds
maximumAge: 30 * 1000 // 30 seconds
};
function success(position) {
console.log(position);
c_pos = position.coords;
mapboxgl.accessToken = 'token'; ///////////////// put your token here
if (!mapboxgl.supported()) {
alert('Your browser does not support Mapbox GL');
} else {
var map = new mapboxgl.Map({
container: 'map', // container id
style: 'mapbox://styles/mapbox/streets-v11',
center: [c_pos.longitude, c_pos.latitude],
zoom: 12 // starting zoom
});
}
}
function error(positionError) {
console.log(positionError.message);
}
if (geolocation) {
geolocation.getCurrentPosition(success, error, positionOptions);
}
} else {
alert("Getting Geolocation is prevented on your browser");
}
return c_pos;
}
</script>
</head>
<body>
<div id='map'></div>
<script>
var current_pos = get_location();
</script>
</body>
</html>
try with this
navigator.geolocation.getCurrentPosition(position => {
const userCoordinates = [position.coords.longitude, position.coords.latitude];
map.addSource("user-coordinates", {
type: "geojson",
data: {
type: "Feature",
geometry: {
type: "Point",
coordinates: userCoordinates
}
}
});
map.addLayer({
id: "user-coordinates",
source: "user-coordinates",
type: "circle"
});
map.flyTo({
center: userCoordinates,
zoom: 14
});
});
Yes, you have to use trigger() to activate the tracking in a programmed way.
// Initialize the geolocate control.
var geolocate = new mapboxgl.GeolocateControl({
positionOptions: {
enableHighAccuracy: true
},
trackUserLocation: true
});
// Add the control to the map.
map.addControl(geolocate);
map.on('load', function() {
geolocate.trigger(); //<- Automatically activates geolocation
});
see https://docs.mapbox.com/mapbox-gl-js/api/markers/#geolocatecontrol-instance-members
I want to set different hovers for different marker icons i use on my map.
This is my marker icon array
//Marker Icons
var markerIcon = {
unvisitedMarker: {
url: 'img/marker.png',
size: new google.maps.Size(30, 30),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(15, 15)
},
unvisitedMarkerHover: {
url: 'img/marker.png',
size: new google.maps.Size(30, 30),
origin: new google.maps.Point(30, 0),
anchor: new google.maps.Point(15, 15)
},
activeMarker: {
url: 'img/marker.png',
size: new google.maps.Size(30, 30),
origin: new google.maps.Point(60, 0),
anchor: new google.maps.Point(15, 15)
},
visitedMarker: {
url: 'img/marker.png',
size: new google.maps.Size(30, 30),
origin: new google.maps.Point(90, 0),
anchor: new google.maps.Point(15, 15)
},
visitedMarkerHover: {
url: 'img/marker.png',
size: new google.maps.Size(30, 30),
origin: new google.maps.Point(120, 0),
anchor: new google.maps.Point(15, 15)
}
I got all icons in one sprite.
I want to set the hover effect for the 'unvisitedMarker' with 'unvisitedMarkerHover' and for 'visitedMarker with 'visitedMarkerHover'. If the marker has the 'activeMarker' icon it should not get a hover effect.
My Problem with this is - i don't know how to set the "if" requirement for that.
//marker hover effect
marker.addListener('mouseover', function() {
if (???) { ... }
});
marker.addListener('mouseout', function() {
if (???) { ... }
});
After that i know i can set the icon with:
marker.setIcon(markerIcon['unvisitedMarker']);
So if someone could help me with the if requirement - that would be awesome!
This one is not that simple. Since I don't have the details such as the URL to your images, I created a sample application in which we have at least 90% similarity. Important: Please don't use the images I've used to avoid copyright issues.
First, I've created public variables: map, markers. "markers" is an empty array.
var map;
var markers = [];
I've also created my own version of markerIcon object.
var markerIcon = {
url : 'http://oi68.tinypic.com/30idv0z.jpg',
unvisitedMarkerHover: 'http://oi65.tinypic.com/jgo3r8.jpg',
originlUrl: 'http://oi68.tinypic.com/30idv0z.jpg',
visitedMarkerHover: 'http://oi65.tinypic.com/ejbn88.jpg',
status: {
unvisitedMarker : {
statusName: 'unvisitedMarker',
},
activeMarker : {
statusName: 'activeMarker',
},
visitedMarker : {
statusName: 'visitedMarker',
}
}
};
I've used a coordinate in San Francisco for my map's center and for Google Maps Javascript API Places Library. I've used Nearby Search as a Place Search and used San Francisco's coordinate for the location property. The radius is set to 500 (measured in meters). This is essential as a combination of the location property - specifying the center of the circle as a LatLng object. For the types, i restricted it only to stores. To learn more about supported types, please check list of supported types.
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: myLatLng,
radius: '500',
type: ['store']
}, callback);
In Nearby Search callback, it returns an array of results. This is what I did:
function createMarker(place, markerId) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
id: markerId,
map: map,
position: placeLoc,
title: 'Hello World!',
anchor: new google.maps.Point(15, 15),
icon: {
url : markerIcon.url,
},
currentStatus: '',
status: markerIcon.status.unvisitedMarker.statusName,
size: new google.maps.Size(30,30),
});
markers.push(marker);
}
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i],i);
}
}
}
I created a createMarker() function that accepts two arguments: the
place object, and markerId.
What the function does is it creates a new Google Maps Javascript
API
Marker
and then set the property and its values accordingly. And also, after
creating the new "marker" object, it will be pushed in to
markers array.
You will also notice that I've added custom properties:
currentStatus, and status. This will play a very important role in
our mouse events.
Since the callback results is an array, I iterate through each array
and called createMarker() function.
This is where the fun begins, in createMarker(), I've also added lines for Google Maps Javascript API Events. This is what I did on my end. Whenever there's a mouseover on a marker, it checks first the currentStatus property of the mouseovered marker. If the currentStatus is an empty string '', it will do another checking for the status property. If the status is 'unvisited', the current icon will now change to a new one. When a mouseout has been detected, the new icon will change to the original one.
Meanwhile, when a marker is clicked, the currentStatus property will be updated to "activeMarker" and then the "status" property is changed to "visitedMarker" as well. You will notice that if the marker has an "activeMarker" currentStatus, nothing will happen when there's a mouseover.
In order to remove the "activeMarker" currentStatus, you will have to click another marker. The "activeMarker" now is transferred to this "another marker". You will also notice that there's a new mouseover effect on the previous marker because I've set a new icon if the marker's status is "unvisitedMarker". You can all find all icon URLs in the markerIcon object.
google.maps.event.addListener(marker, 'mouseover', function() {
if ( this.currentStatus !== markerIcon.status.activeMarker.statusName ) {
if ( this.status === markerIcon.status.unvisitedMarker.statusName ) {
this.setIcon(markerIcon.unvisitedMarkerHover);
} else {
this.setIcon(markerIcon.visitedMarkerHover);
}
this.setPosition(this.position);
console.log(this.currentStatus, this.status, this.id);
}
});
google.maps.event.addListener(marker, 'mouseout', function() {
this.setIcon(markerIcon.originlUrl);
});
google.maps.event.addListener(marker, 'click', function() {
for ( var i = 0; i < markers.length; i++ ) {
markers[i].currentStatus = '';
}
this.currentStatus = markerIcon.status.activeMarker.statusName;
this.status = markerIcon.status.visitedMarker.statusName;
console.log(this.currentStatus, this.status);
});
Whole code below:
var map;
var markers = [];
var markerIcon = {
url : 'http://oi68.tinypic.com/30idv0z.jpg',
unvisitedMarkerHover: 'http://oi65.tinypic.com/jgo3r8.jpg',
originlUrl: 'http://oi68.tinypic.com/30idv0z.jpg',
visitedMarkerHover: 'http://oi65.tinypic.com/ejbn88.jpg',
status: {
unvisitedMarker : {
//origin: new google.maps.Point(0, 0),
statusName: 'unvisitedMarker',
},
activeMarker : {
//origin: new google.maps.Point(60, 0),
statusName: 'activeMarker',
},
visitedMarker : {
//origin: new google.maps.Point(90, 0),
statusName: 'visitedMarker',
},
}
};
function initMap() {
var myLatLng = {lat: 37.773972, lng: -122.431297};
map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: myLatLng
});
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: myLatLng,
radius: '500',
type: ['store']
}, callback);
}
function createMarker(place, markerId) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
id: markerId,
map: map,
position: placeLoc,
title: 'Hello World!',
anchor: new google.maps.Point(15, 15),
icon: {
url : markerIcon.url,
},
currentStatus: '',
status: markerIcon.status.unvisitedMarker.statusName,
size: new google.maps.Size(30,30),
});
markers.push(marker);
google.maps.event.addListener(marker, 'mouseover', function() {
if ( this.currentStatus !== markerIcon.status.activeMarker.statusName ) {
if ( this.status === markerIcon.status.unvisitedMarker.statusName ) {
this.setIcon(markerIcon.unvisitedMarkerHover);
} else {
this.setIcon(markerIcon.visitedMarkerHover);
}
this.setPosition(this.position);
//console.log(this.currentStatus, this.status, this.id);
}
});
google.maps.event.addListener(marker, 'mouseout', function() {
this.setIcon(markerIcon.originlUrl);
});
google.maps.event.addListener(marker, 'click', function() {
for ( var i = 0; i < markers.length; i++ ) {
markers[i].currentStatus = '';
}
this.currentStatus = markerIcon.status.activeMarker.statusName;
this.status = markerIcon.status.visitedMarker.statusName;
});
}
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i],i);
}
}
}
/* 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;
}
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCzjs-bUR6iIl8yGLr60p6-zbdFtRpuXTQ&callback=initMap"
async defer></script>
Hope this application could help and happy coding!
I have a ol 3.10.1 map where the goal is to redraw the features of a layer dynamically. On the road to get there, I'm using the source.clear() function. The strange thing is that the source.clear() actually clear the features from the layer at the current zoom level, but while zooming in or out the features are still there. Am I using the source.clear() function the correct way? Please find bellow the code snippet which I'm using for testing purposes.
var image = new ol.style.Circle({
radius: 5,
fill: null,
stroke: new ol.style.Stroke({color: 'red', width: 1})
});
var styles = {
'Point': [new ol.style.Style({
image: image
})]};
var styleFunction = function(feature, resolution) {
return styles[feature.getGeometry().getType()];
};
var CITYClusterSource = new ol.source.Cluster({
source: new ol.source.Vector({
url: 'world_cities.json',
format: new ol.format.GeoJSON(),
projection: 'EPSG:3857'
}),
})
var CITYClusterLayer = new ol.layer.Vector({
source: CITYClusterSource,
style: styleFunction
});
setTimeout(function () { CITYClusterSource.clear(); }, 5000);
var map = new ol.Map({
target: 'map',
renderer: 'canvas',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM(),
}),
CITYClusterLayer
],
view: new ol.View({
center: ol.proj.transform([15.0, 45.0], 'EPSG:4326', 'EPSG:3857'),
zoom:3
})
});
I'm using the setTimout() function to have the features visible for some seconds, before they are supposed to be cleared.
Please advice.
UPDATE: http://jsfiddle.net/jonataswalker/ayewaz87/
I forgot, OL will load your features again and again, for each resolution. So if you want to remove once and for all, use a custom loader, see fiddle.
Your source is asynchronously loaded, so set a timeout when it's ready:
CITYClusterSource.once('change', function(evt){
if (CITYClusterSource.getState() === 'ready') {
// now the source is fully loaded
setTimeout(function () { CITYClusterSource.clear(); }, 5000);
}
});
Note the once method, you can use on instead of it.
I need to recalculate the directions, when another marker is clicked or when my origin marker is dragged to another location.
at the moment, I am inserting a marker when a user inserts his/her address then when the users clicks on any existing marker it calculates the directions. Unfortunately it doesn't clear the previous directions.
Any Help at all will be greatly appreciated.
Here's the code:
jQuery(document).ready(function() {
jQuery.getJSON('./index.php', {
option: "com_locate",
view: "branches",
tmpl: "component",
format: "json",
},
function(json){
jQuery(function(){
jQuery("#googleMap").gmap3({
map:{
options: {
center:[-29.8191,25.3499],
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
streetViewControl: false
}
},
marker: {
values: json,
options: {
icon: new google.maps.MarkerImage("http://maps.gstatic.com/mapfiles/icon_green.png")
},
events:{
mouseover: function(marker, event, context){
jQuery(this).gmap3(
{clear:"overlay"},
{
overlay:{
id: "tooltip",
latLng: marker.getPosition(),
options:{
content: "<div class='infobulle"+(context.data.drive ? " drive" : "")+"'>" +
"<div class='bg'></div>" +
"<div class='text'>" + context.data.city + " (" + context.data.telephone + ")</div>" +
"</div>" +
"<div class='arrow'></div>",
offset: {
x:-46,
y:-73
}
}
}
});
},
mouseout: function(){
jQuery(this).gmap3({clear:"overlay"});
},
click: function(marker, event, context){
markerSelected(context.id);
}
}
}
});
///////////////
jQuery('#test-ok').click(function(){
var addr = jQuery('#test-address').val();
if ( !addr || !addr.length ) return;
jQuery("#googleMap").gmap3({
getlatlng:{
address: addr,
callback: function(results){
if ( !results ) return;
jQuery("#googleMap").gmap3({
clear:{id:"user"}
},
{
marker:{
latLng:results[0].geometry.location,
id:"user",
name:"user",
options:{
draggable: true
}
},
map:{
center: true,
zoom: 5
}
});
}
}
});
});
jQuery('#test-address').keypress(function(e){
if (e.keyCode == 13){
jQuery('#test-ok').click();
}
});
///////////////
///////////////
function markerSelected(id){
var marker = jQuery('#googleMap').gmap3({get:id});
var usermarker = jQuery('#googleMap').gmap3({get:"user"});
jQuery("#googleMap").gmap3({
getroute:{
options:{
origin:[usermarker.getPosition().lat(),usermarker.getPosition().lng()],
destination:[marker.getPosition().lat(),marker.getPosition().lng()],
travelMode: google.maps.DirectionsTravelMode.DRIVING
},
callback: function(results){
if (!results) return;
jQuery(this).gmap3({
map:{
options:{
}
},
directionsrenderer:{
container: jQuery(document.createElement("div")).addClass("googlemap").insertAfter(jQuery("#googleMap")),
options:{
directions:results
}
}
});
}
}
});
}
});
});
});
The code you're using creates a new DOM element each time you do a directions request, without removing any existing such elements or replacing content in any existing elements. The pertinent part of your code is this:
directionsrenderer:{
container: jQuery(document.createElement("div")).addClass("googlemap").insertAfter(jQuery("#googleMap")),
// The above creates a new DOM element every time markerSelected() is called!
options:{
directions:results
}
}
You want to create that only once. If you want, you can do it directly in the HTML markup.
Use the below as a replacement for your getroute callback function. I've plugged in a unique ID for the container element and left the "googlemap" class intact in case it's needed for CSS or other sections of code. Since you specifically want only one set of directions to be visible, though, let's select your container by ID.
callback: function(results){
if (!results) return;
if (!jQuery("#dircontainer").length>0) {
jQuery("<div id='dircontainer' class='googlemap'></div>").insertAfter("#googleMap");
} // Creates your directions container if it doesn't already exist.
else {
jQuery("#dircontainer").html("");
} /* I'm clearing the existing contents of the container in case gmap3 doesn't
automatically clear it when the new directions are inserted.
You can experiment with removing this else statement. */
jQuery(this).gmap3({
map:{
options:{
}
},
directionsrenderer:{
container: jQuery("#dircontainer"),
options:{
directions:results
}
}
});
}
I'm making some assumptions here about the way the gmap3 plugin works; I've worked with jQuery and the Google Maps JS API, but not with this plugin.