issue with click event in nokia maps api - javascript

i try this code
for(i=0; i<num ;i++)
{
points.push([lats[i], lngs[i]]);
if(i==0) str = 'S';
else if(i==num-1) str = 'E';
else str = '';
var marker = new nokia.maps.map.Marker(
[lats[i], lngs[i]],
{
title: str,
visibility: true,
icon: img,
anchor: new nokia.maps.util.Point(5, 5)
});
marker.addListener('click', function(evt){
$('.loc').html(times[i]);
});
map.objects.add(marker);
}
but it just does not fire click event. is anything wrong with code?
lats and lngs and times are defined and points is to be used later.
Edit:
Problem solved. See comment for answer below.

It looks like the problem is with the line:
$('.loc').html(times[i]);
Within the marker listener. The event hasn't got access to the array element when it is fired and therefore fails. I think you need to add an attribute to the marker and access it as shown:
var marker = new nokia.maps.map.Marker(
[lats[i], lngs[i]],
{
title: str,
visibility: true,
icon: img,
anchor: new nokia.maps.util.Point(29, 71),
$html : times[i]
});
marker.addListener('click', function(evt){
//$('.loc').html(times[i]);
alert (evt.target.$html);
});
Try the following (with your own App Id and token of course):
<!DOCTYPE HTML SYSTEM>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=7; IE=EmulateIE9" />
<script type="text/javascript" charset="UTF-8" src="http://api.maps.nokia.com/2.2.3/jsl.js"></script>
<style type="text/css">
html {
overflow:hidden;
}
body {
margin: 0;
padding: 0;
overflow: hidden;
width: 100%;
height: 100%;
position: absolute;
}
#mapContainer {
width:100%;
height: 100%;
left: 0;
top: 0;
position: absolute;
}
</style>
</head>
<body>
<div id="mapContainer"></div>
<script type="text/javascript">
nokia.Settings.set( "appId", "YOUR APP ID GOES HERE");
nokia.Settings.set( "authenticationToken", "YOUR AUTHENTICATION TOKEN GOES HERE");
var mapContainer = document.getElementById("mapContainer");
var DefaultLatitude = 52.516237;
var DefaultLongitude = 13.377686;
var defaultZoomLevel = 16;
var mapOptions =
{
baseMapType: nokia.maps.map.Display.NORMAL,
center: new nokia.maps.geo.Coordinate(DefaultLatitude, DefaultLongitude),
zoomLevel: defaultZoomLevel,
components: [
new nokia.maps.map.component.ZoomBar(),
new nokia.maps.map.component.Behavior(),
new nokia.maps.map.component.Overview(),
new nokia.maps.map.component.ScaleBar(),
new nokia.maps.map.component.ContextMenu()
]
};
var map = new nokia.maps.map.Display(mapContainer, mapOptions);
var str ="";
var img = "http://api.maps.nokia.com/en/playground/examples/maps/res/markerHouse.png";
var points= new Array();
var lats = new Array();
var lngs = new Array();
var times = new Array();
var num;
lats[0] = 52.516237;
lngs[0] = 13.377686;
times[0] = "brandenburg gate";
num = 1;
for(var i=0; i<num ;i++)
{
points.push([lats[i], lngs[i]]);
if(i==0) str = 'S';
else if(i==num-1) str = 'E';
else str = '';
var marker = new nokia.maps.map.Marker(
[lats[i], lngs[i]],
{
title: str,
visibility: true,
icon: img,
anchor: new nokia.maps.util.Point(29, 71),
$html : times[i]
});
marker.addListener('click', function(evt){
//$('.loc').html(times[i]);
alert (evt.target.$html);
});
map.objects.add(marker);
}
</script>
</body>
</html>

Related

Change mapbox on google maps

I am trying swich map box to google maps in some map app.
This shows polyline on map, but i have one problem.
Here is my code :
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<style>
/* 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;
}
</style>
</head>
<body>
<div id="map"></div>
<script src="https://portal.company.io/theme/plugins/moment.js"></script>
<script src="https://portal.company.io/Scripts/googlemap/mapstyle.js"></script>
<script src="https://portal.company.io/Scripts/googlemap/markerclusterer.js"></script>
<script type="text/javascript">
(function(t,e){"function"==typeof define&&define.amd?define(["leaflet"],t):"object"==typeof exports&&(module.exports=t(require("leaflet"))),e!==void 0&&e.L&&(e.LeafletLabel=t(L))})(function(t){t.labelVersion="0.2.4";var e=t.Class.extend({includes:t.Mixin.Events,options:{className:"",clickable:!1,direction:"right",noHide:!1,offset:[12,-15],opacity:1,zoomAnimation:!0},initialize:function(e,i){t.setOptions(this,e),this._source=i,this._animated=t.Browser.any3d&&this.options.zoomAnimation,this._isOpen=!1},onAdd:function(e){this._map=e,this._pane=this.options.pane?e._panes[this.options.pane]:this._source instanceof t.Marker?e._panes.markerPane:e._panes.popupPane,this._container||this._initLayout(),this._pane.appendChild(this._container),this._initInteraction(),this._update(),this.setOpacity(this.options.opacity),e.on("moveend",this._onMoveEnd,this).on("viewreset",this._onViewReset,this),this._animated&&e.on("zoomanim",this._zoomAnimation,this),t.Browser.touch&&!this.options.noHide&&(t.DomEvent.on(this._container,"click",this.close,this),e.on("click",this.close,this))},onRemove:function(t){this._pane.removeChild(this._container),t.off({zoomanim:this._zoomAnimation,moveend:this._onMoveEnd,viewreset:this._onViewReset},this),this._removeInteraction(),this._map=null},setLatLng:function(e){return this._latlng=t.latLng(e),this._map&&this._updatePosition(),this},setContent:function(t){return this._previousContent=this._content,this._content=t,this._updateContent(),this},close:function(){var e=this._map;e&&(t.Browser.touch&&!this.options.noHide&&(t.DomEvent.off(this._container,"click",this.close),e.off("click",this.close,this)),e.removeLayer(this))},updateZIndex:function(t){this._zIndex=t,this._container&&this._zIndex&&(this._container.style.zIndex=t)},setOpacity:function(e){this.options.opacity=e,this._container&&t.DomUtil.setOpacity(this._container,e)},_initLayout:function(){this._container=t.DomUtil.create("div","leaflet-label "+this.options.className+" leaflet-zoom-animated"),this.updateZIndex(this._zIndex)},_update:function(){this._map&&(this._container.style.visibility="hidden",this._updateContent(),this._updatePosition(),this._container.style.visibility="")},_updateContent:function(){this._content&&this._map&&this._prevContent!==this._content&&"string"==typeof this._content&&(this._container.innerHTML=this._content,this._prevContent=this._content,this._labelWidth=this._container.offsetWidth)},_updatePosition:function(){var t=this._map.latLngToLayerPoint(this._latlng);this._setPosition(t)},_setPosition:function(e){var i=this._map,n=this._container,o=i.latLngToContainerPoint(i.getCenter()),s=i.layerPointToContainerPoint(e),a=this.options.direction,l=this._labelWidth,h=t.point(this.options.offset);"right"===a||"auto"===a&&s.x<o.x?(t.DomUtil.addClass(n,"leaflet-label-right"),t.DomUtil.removeClass(n,"leaflet-label-left"),e=e.add(h)):(t.DomUtil.addClass(n,"leaflet-label-left"),t.DomUtil.removeClass(n,"leaflet-label-right"),e=e.add(t.point(-h.x-l,h.y))),t.DomUtil.setPosition(n,e)},_zoomAnimation:function(t){var e=this._map._latLngToNewLayerPoint(this._latlng,t.zoom,t.center).round();this._setPosition(e)},_onMoveEnd:function(){this._animated&&"auto"!==this.options.direction||this._updatePosition()},_onViewReset:function(t){t&&t.hard&&this._update()},_initInteraction:function(){if(this.options.clickable){var e=this._container,i=["dblclick","mousedown","mouseover","mouseout","contextmenu"];t.DomUtil.addClass(e,"leaflet-clickable"),t.DomEvent.on(e,"click",this._onMouseClick,this);for(var n=0;i.length>n;n++)t.DomEvent.on(e,i[n],this._fireMouseEvent,this)}},_removeInteraction:function(){if(this.options.clickable){var e=this._container,i=["dblclick","mousedown","mouseover","mouseout","contextmenu"];t.DomUtil.removeClass(e,"leaflet-clickable"),t.DomEvent.off(e,"click",this._onMouseClick,this);for(var n=0;i.length>n;n++)t.DomEvent.off(e,i[n],this._fireMouseEvent,this)}},_onMouseClick:function(e){this.hasEventListeners(e.type)&&t.DomEvent.stopPropagation(e),this.fire(e.type,{originalEvent:e})},_fireMouseEvent:function(e){this.fire(e.type,{originalEvent:e}),"contextmenu"===e.type&&this.hasEventListeners(e.type)&&t.DomEvent.preventDefault(e),"mousedown"!==e.type?t.DomEvent.stopPropagation(e):t.DomEvent.preventDefault(e)}});return t.BaseMarkerMethods={showLabel:function(){return this.label&&this._map&&(this.label.setLatLng(this._latlng),this._map.showLabel(this.label)),this},hideLabel:function(){return this.label&&this.label.close(),this},setLabelNoHide:function(t){this._labelNoHide!==t&&(this._labelNoHide=t,t?(this._removeLabelRevealHandlers(),this.showLabel()):(this._addLabelRevealHandlers(),this.hideLabel()))},bindLabel:function(i,n){var o=this.options.icon?this.options.icon.options.labelAnchor:this.options.labelAnchor,s=t.point(o)||t.point(0,0);return s=s.add(e.prototype.options.offset),n&&n.offset&&(s=s.add(n.offset)),n=t.Util.extend({offset:s},n),this._labelNoHide=n.noHide,this.label||(this._labelNoHide||this._addLabelRevealHandlers(),this.on("remove",this.hideLabel,this).on("move",this._moveLabel,this).on("add",this._onMarkerAdd,this),this._hasLabelHandlers=!0),this.label=new e(n,this).setContent(i),this},unbindLabel:function(){return this.label&&(this.hideLabel(),this.label=null,this._hasLabelHandlers&&(this._labelNoHide||this._removeLabelRevealHandlers(),this.off("remove",this.hideLabel,this).off("move",this._moveLabel,this).off("add",this._onMarkerAdd,this)),this._hasLabelHandlers=!1),this},updateLabelContent:function(t){this.label&&this.label.setContent(t)},getLabel:function(){return this.label},_onMarkerAdd:function(){this._labelNoHide&&this.showLabel()},_addLabelRevealHandlers:function(){this.on("mouseover",this.showLabel,this).on("mouseout",this.hideLabel,this),t.Browser.touch&&this.on("click",this.showLabel,this)},_removeLabelRevealHandlers:function(){this.off("mouseover",this.showLabel,this).off("mouseout",this.hideLabel,this),t.Browser.touch&&this.off("click",this.showLabel,this)},_moveLabel:function(t){this.label.setLatLng(t.latlng)}},t.Icon.Default.mergeOptions({labelAnchor:new t.Point(9,-20)}),t.Marker.mergeOptions({icon:new t.Icon.Default}),t.Marker.include(t.BaseMarkerMethods),t.Marker.include({_originalUpdateZIndex:t.Marker.prototype._updateZIndex,_updateZIndex:function(t){var e=this._zIndex+t;this._originalUpdateZIndex(t),this.label&&this.label.updateZIndex(e)},_originalSetOpacity:t.Marker.prototype.setOpacity,setOpacity:function(t,e){this.options.labelHasSemiTransparency=e,this._originalSetOpacity(t)},_originalUpdateOpacity:t.Marker.prototype._updateOpacity,_updateOpacity:function(){var t=0===this.options.opacity?0:1;this._originalUpdateOpacity(),this.label&&this.label.setOpacity(this.options.labelHasSemiTransparency?this.options.opacity:t)},_originalSetLatLng:t.Marker.prototype.setLatLng,setLatLng:function(t){return this.label&&!this._labelNoHide&&this.hideLabel(),this._originalSetLatLng(t)}}),t.CircleMarker.mergeOptions({labelAnchor:new t.Point(0,0)}),t.CircleMarker.include(t.BaseMarkerMethods),t.Path.include({bindLabel:function(i,n){return this.label&&this.label.options===n||(this.label=new e(n,this)),this.label.setContent(i),this._showLabelAdded||(this.on("mouseover",this._showLabel,this).on("mousemove",this._moveLabel,this).on("mouseout remove",this._hideLabel,this),t.Browser.touch&&this.on("click",this._showLabel,this),this._showLabelAdded=!0),this},unbindLabel:function(){return this.label&&(this._hideLabel(),this.label=null,this._showLabelAdded=!1,this.off("mouseover",this._showLabel,this).off("mousemove",this._moveLabel,this).off("mouseout remove",this._hideLabel,this)),this},updateLabelContent:function(t){this.label&&this.label.setContent(t)},_showLabel:function(t){this.label.setLatLng(t.latlng),this._map.showLabel(this.label)},_moveLabel:function(t){this.label.setLatLng(t.latlng)},_hideLabel:function(){this.label.close()}}),t.Map.include({showLabel:function(t){return this.addLayer(t)}}),t.FeatureGroup.include({clearLayers:function(){return this.unbindLabel(),this.eachLayer(this.removeLayer,this),this},bindLabel:function(t,e){return this.invoke("bindLabel",t,e)},unbindLabel:function(){return this.invoke("unbindLabel")},updateLabelContent:function(t){this.invoke("updateLabelContent",t)}}),e},window);
</script>
<script>
var itm = [{"TrackingAvgSpeed":-1.0,"OverspeedPercent":0,"AvgAllowedSpeed":50.0,"DistanceInMeters":43,"Points":0.0,"Polyline":"qobxHcdujCADC???ICKK??COEMGI??EEGAE?","CalculatedAvgSpeed":21.6},{"TrackingAvgSpeed":-1.0,"OverspeedPercent":0,"AvgAllowedSpeed":50.0,"DistanceInMeters":35,"Points":0.0,"Polyline":"sqbxH}eujCG???GDGFEJ??CJAJ?J#J","CalculatedAvgSpeed":21.6},{"TrackingAvgSpeed":-1.0,"OverspeedPercent":0,"AvgAllowedSpeed":50.0,"DistanceInMeters":257,"Points":0.0,"Polyline":"urbxHscujC#LDHDH??#L?^??A`#GlBKdCKzCIvAInAI|#","CalculatedAvgSpeed":31.68},{"TrackingAvgSpeed":-1.0,"OverspeedPercent":100,"AvgAllowedSpeed":50.0,"DistanceInMeters":300,"Points":0.0,"Polyline":"etbxHkltjCGt#Kx#Ix#O~#Kp#Kr#Qv#]hBaAfF??M\\??G#GBGDEH","CalculatedAvgSpeed":65.73333},{"TrackingAvgSpeed":-1.0,"OverspeedPercent":0,"AvgAllowedSpeed":50.0,"DistanceInMeters":42,"Points":0.0,"Polyline":"i{bxH}ssjCCHCHAJ???NBN??BL??Cj#","CalculatedAvgSpeed":29.4},{"TrackingAvgSpeed":-1.0,"OverspeedPercent":0,"AvgAllowedSpeed":50.0,"DistanceInMeters":105,"Points":0.0,"Polyline":"o{bxHcpsjCqApG","CalculatedAvgSpeed":43.2},{"TrackingAvgSpeed":-1.0,"OverspeedPercent":100,"AvgAllowedSpeed":50.0,"DistanceInMeters":656,"Points":0.0,"Polyline":"a~bxHqgsjCUpA??Ot#Sv#Uz#Wv#??KZ??IV??i#bBW~#Ol#Mp#??G\\Gr#Ej#Cv#?r#??GdCCp#El#Gh#Eh#??Kl#Id#Kf#??Kb#Mb#K^MZO^Q^Wd#??S\\UXWXUT]\\","CalculatedAvgSpeed":68.21053},{"TrackingAvgSpeed":-1.0,"OverspeedPercent":100,"AvgAllowedSpeed":70.0,"DistanceInMeters":716,"Points":0.0,"Polyline":"_ocxHusqjCi#b#cG|EsHbGs#l#a#`#YZSXU\\U^Sb#Sd#Q`#M`#Md#Oh#Kf#??ET??Od#Ox#QdAGl#C\\AZ","CalculatedAvgSpeed":79.8},{"TrackingAvgSpeed":-1.0,"OverspeedPercent":100,"AvgAllowedSpeed":70.0,"DistanceInMeters":21,"Points":0.0,"Polyline":"imdxHalpjCAT?h#","CalculatedAvgSpeed":72.0},{"TrackingAvgSpeed":-1.0,"OverspeedPercent":62,"AvgAllowedSpeed":92.16,"DistanceInMeters":2465,"Points":0.0,"Polyline":"kmdxHajpjC?`A??#nAHrCTpH??HtG??f#db#^rZ??FbGNvL#x#Dx#Br#Dn#??Dn#JbAJfATjBrBnQ??`Flc#??bBxN??RfB??`BjN","CalculatedAvgSpeed":93.24},{"TrackingAvgSpeed":-1.0,"OverspeedPercent":100,"AvgAllowedSpeed":72.76,"DistanceInMeters":2533,"Points":0.0,"Polyline":"iucxHqpijC#F??vCbWfBbORdBZ`C??xAlK\\rCVzBn#jG~ArO??h#fF??h#dFfAjJ??tApL??`Ex]??h#vE??jBjP??D^??|#rH??vB`R","CalculatedAvgSpeed":100.28},{"TrackingAvgSpeed":-1.0,"OverspeedPercent":100,"AvgAllowedSpeed":90.0,"DistanceInMeters":1133,"Points":0.0,"Polyline":"qjbxH{vbjC\\xC??RfB??p#|F??fAnJ??X|B??b#vD??l#dF??f#lE??pArKVxB??H|#Jv#Bd#B^Bb#FdBDtA??FbCBr#???Z?\\A`#Af#Er#K|A??UrC","CalculatedAvgSpeed":98.42553},{"TrackingAvgSpeed":-1.0,"OverspeedPercent":0,"AvgAllowedSpeed":93.94,"DistanceInMeters":1036,"Points":0.0,"Polyline":"w|axHus_jCSdC??_AxJ??YvC??YnC??cAfKCV??qAxM??QdB??ShB??a#dE??WbC??EV??U|B??YjC??C`#??K~#??MdA??c#fE","CalculatedAvgSpeed":84.43636},{"TrackingAvgSpeed":-1.0,"OverspeedPercent":0,"AvgAllowedSpeed":90.0,"DistanceInMeters":2011,"Points":0.0,"Polyline":"qlbxHgy|iC[zC??Gl#??c#hE??[xC??Gj#??AL??MpA??Gj#??Iv#??CR??OrA??CZ??O|A??e#hE??W`C??CV??OvAC\\E`#AT??A\\C^Ad#UjJ??UzI??Cl#??_#bOAd#Cp#Cp#C\\C`#Cb#CTEZ??CR??[pB_#bC??w#|E??aAjG??g#vC??e#lC??a#|B??Kj#??EX??i#zC??GZ??a#`C??_AhF??[bB??SfA??u#hE??s#dE","CalculatedAvgSpeed":80.48},{"TrackingAvgSpeed":-1.0,"OverspeedPercent":82,"AvgAllowedSpeed":57.02,"DistanceInMeters":245,"Points":0.0,"Polyline":"glcxHyjwiCG\\Mr#Gf#??Gv#Cf#Af#Ab##f#?b##f#Bb#??Dj#??D`#D\\F`#Jd#Jd#Ld#","CalculatedAvgSpeed":56.475},{"TrackingAvgSpeed":-1.0,"OverspeedPercent":86,"AvgAllowedSpeed":52.73,"DistanceInMeters":1282,"Points":0.0,"Polyline":"mkcxH{tviCNf#N^NZLV??LR??JR??bA`B^r#??|#zA??f#`A??LR??HP??f#~#??P`#Tf#??NXN\\??Vn#??DL??Xr#Rb#??t#pB??Rf#??r#fB??Rh#??Pb#??LX??p#dB??HR??#D??JV??HP??`#fA??LX??j#zA??LX??n#bB??`AdC??Pd#??N^??FN??Vn#??FP??`#`A??|#|B??~#`C??Xt#??^bA??Zt#??h#vA??^~#??Nb#??h#rA??~#bC","CalculatedAvgSpeed":53.16},{"TrackingAvgSpeed":-1.0,"OverspeedPercent":41,"AvgAllowedSpeed":83.09,"DistanceInMeters":1446,"Points":0.0,"Polyline":"q|axHqzsiCTh#??Rh#??JZ??`#bA??FN??Tj#??t#jB??j#vA??rHfRPb#L^L`#J\\J^Pr#b#fB??z#dD??r#rC??nB`I??lA~E??fCbK??XjA??p#jCXdAz#xC??p#xB??fAnD??\\hA??Rr#PE","CalculatedAvgSpeed":83.82857}];
var polylines = [], points = [], behavePolylines = [];
$(function(){
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
}
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
};
function getColor(calculated, allowed){
var diff = calculated - allowed;
if(diff <=0){
return "#0ea00f";
} else if(diff >0 && diff <= 15){
return "#ff6a00"
} else if(diff > 15){
return "#ff0000"
} else return "#000"
}
function renderTrip (trip) {
//if (!data.success) return;
// var trip = JSON.parse(data.trip);
$.each(polylines, function (e, val) {
map.removeLayer(val);
});
var tripPolyPoints = L.PolylineUtil.decode(data.POLY);
var tripPoly = L.polyline(tripPolyPoints,
{
color: "#000000",
opacity: 0.6,
weight: 4
});
tripPoly.addTo(map);
map.fitBounds(tripPoly.getBounds());
polylines.push(tripPoly);
for (var i = 0; i < trip.length; i++) {
var calculated = (trip[i].CalculatedAvgSpeed).toFixed(1);
var allowed = (trip[i].AvgAllowedSpeed).toFixed(1);
var distance = (trip[i].DistanceInMeters / 1000.0).toFixed(2);
var polylinePoints = L.PolylineUtil.decode(trip[i].Polyline);
var polyline = L.polyline(polylinePoints, {
color: getColor(calculated, allowed),
opacity: 1,
weight: 8
}).bindLabel('Średnia prędkość: ' + calculated + ' KM/H<br>Średnia dopuszczalna prędkość: '
+ allowed + ' KM/H<br>Długość odcinka: ' + distance + ' KM');
polyline.addTo(map);
polylines.push(polyline);
}
var origPolyPoints = L.PolylineUtil.decode(data.bfPoly);
var origPoly = L.polyline(origPolyPoints,
{
color: "#0000ff",
opacity: 0.5,
weight: 5
});
origPoly.addTo(map);
polylines.push(origPoly);
}
renderTrip(itm);
});
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=MY_KAY&callback=initMap"
async defer></script>
</body>
</html>
Error Message :
Uncaught (in promise) yd {message: "initMap is not a function", name:
"InvalidValueError", stack: "Error↵ at new yd message: "initMap is
not a function" name: "InvalidValueError"
Your initMap function needs to be placed in global scope so that the Map API's callback can find and call this function.
<script>
var itm = [];
var polylines = [],
points = [],
behavePolylines = [];
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: { lat: -34.397, lng: 150.644 },
zoom: 8
});
}
$(function() {
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
};
...
});
</script>
Please check out related thread Google Maps Javascript API not loading reliably
Hope this helps!

JavaScript If statement and Combo box functionality

I have two combo box's working independently. I would like to get them to work together. I either get State name queried or Farm Acreage queried. I cannot get them both to filter together.
Query Texas and 4 Acres. Get all the 4 acre counties in Texas. Right now it will either give me All of Texas or All 4 acre counties in the US.
The if statements are in the "app" object.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no" />
<title>Drop Down Test</title>
<link rel="stylesheet" href="http://js.arcgis.com/3.10/js/dojo/dijit/themes/claro/claro.css">
<link rel="stylesheet" href="http://js.arcgis.com/3.10/js/esri/css/esri.css">
<style>
html,
body,
#mainWindow {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
body {
background-color: #FFF;
overflow: hidden;
font-family: "Trebuchet MS";
}
#header {
height: 3%;
overflow: auto;
}
</style>
<script>
var dojoConfig = {
parseOnLoad: true
};
</script>
<script src="http://js.arcgis.com/3.10/"></script>
<script>
var map;
require([
"esri/map",
"dojo/on",
"esri/tasks/query",
"esri/layers/FeatureLayer",
"dojo/store/Memory",
"dojo/_base/array",
"dojo/_base/lang",
"esri/request",
"dojo/json",
"dijit/layout/BorderContainer",
"dijit/layout/ContentPane",
"dijit/form/Button",
"dijit/form/ComboBox",
"dojo/domReady!"
], function(
Map, on, Query, FeatureLayer, Memory, array, lang, esriRequest, json
) {
map = new Map("map", {
basemap: "topo",
center: [-98.579729, 39.828366],
zoom: 5
});
var crops = new FeatureLayer("https://services.arcgis.com/V6ZHFr6zdgNZuVG0/arcgis/rest/services/USA_County_Crops_2007/FeatureServer/0", {
mode: FeatureLayer.MODE_SELECTION,
outFields: ["*"]
});
map.addLayers([crops]);
map.on("layers-add-result", lang.hitch(this, function(){
var url = "https://services.arcgis.com/V6ZHFr6zdgNZuVG0/arcgis/rest/services/USA_County_Crops_2007/FeatureServer/0/generateRenderer";
var classificationDef = {"type":"uniqueValueDef","uniqueValueFields":["STATE"]};
var classificationDef2 = {"type":"uniqueValueDef","uniqueValueFields":["TotalFarmedAcres"]};
var str = json.stringify(classificationDef);
var str2 = json.stringify(classificationDef2);
esriRequest({
url:url,
content:{
classificationDef:str,
f:'json'
},
handleAs:'json',
callbackParamName:'callback',
timeout:15000
}).then(lang.hitch(this,function(response){
var uniqueValueInfos = response && response.uniqueValueInfos;
if(uniqueValueInfos){
var store2 = new Memory({data:[]});
dijit.byId("uniqueValuesSelect").set('store',store2);
var data = array.map(uniqueValueInfos,lang.hitch(this,function(info,index){
var value = info.value;
//value = parseFloat(value);
var dataItem = {
id:index,
name:value
};
return dataItem;
}));
store2 = new Memory({data:data});
dijit.byId("uniqueValuesSelect").set('store',store2);
}
}),lang.hitch(this,function(error){
console.error(error);
}));
esriRequest({
url:url,
content:{
classificationDef:str2,
f:'json'
},
handleAs:'json',
callbackParamName:'callback',
timeout:15000
}).then(lang.hitch(this,function(response){
var uniqueValueInfos2 = response && response.uniqueValueInfos;
if(uniqueValueInfos2){
var store3 = new Memory({data:[]});
dijit.byId("uniqueValuesSelect2").set('store',store3);
var data2 = array.map(uniqueValueInfos2,lang.hitch(this,function(info,index){
var value2 = info.value;
//value2 = parseFloat(value2);
var dataItem2 = {
id:index,
name:value2
};
return dataItem2;
}));
store3 = new Memory({data:data2});
dijit.byId("uniqueValuesSelect2").set('store',store3);
}
}),lang.hitch(this,function(error){
console.error(error);
}));
}));
app = {
zoomRow: function(id, which){
crops.clearSelection();
var query = new Query();
if(which == "statename"){
query.where = "STATE='" + (id).toString() + "'";
}if(which == "FarmedAcres"){
query.where = "TotalFarmedAcres='" + (id).toString() + "'";
}
console.info(query.where);
query.returnGeometry = true;
crops.selectFeatures(query, FeatureLayer.SELECTION_NEW, function (features) {
//var thePoly = features[0].geometry;
//var theExtent = thePoly.getExtent().expand(2); //Zoom out slightly from the polygon's extent
//map.setExtent(theExtent);
});
}
};
});
</script>
</head>
<body class="claro">
<div id="mainWindow" data-dojo-type="dijit/layout/BorderContainer" data-dojo-props="design:'headline', gutters:false" style="padding:0px;margin:0px;">
<div id="header" data-dojo-type="dijit/layout/ContentPane" data-dojo-props="region:'top'" style="overflow:hidden;border:none;border-bottom: 3px solid #CC9900;font-family: Windows;font-size:14pt; color: #FFFFFF;background: #000000; "> Select a State and total Acres farmed:
<input id="uniqueValuesSelect" data-dojo-type="dijit.form.ComboBox" value="statename" onchange="app.zoomRow(document.getElementById('uniqueValuesSelect').value, 'statename');" />
<input id="uniqueValuesSelect2" data-dojo-type="dijit.form.ComboBox" value="FarmedAcres" onchange="app.zoomRow(document.getElementById('uniqueValuesSelect2').value, 'FarmedAcres');" />
</div>
<div id="map" data-dojo-type="dijit/layout/ContentPane" data-dojo-props="region:'left'" style="width:100%;height:95%;border:none;padding:0px;margin:0px;"></div>
</div>
</body>
</html>
You need to have access to both comboboxes so you can do something like this:
app = {
zoomRow: function(stateId, acresId){
crops.clearSelection();
var query = new Query();
query.where = "STATE='" + (stateId).toString() + "' AND TotalFarmedAcres='" + (acresId).toString() + "'";
console.info(query.where);
query.returnGeometry = true;
crops.selectFeatures(query, FeatureLayer.SELECTION_NEW, function (features) {
//var thePoly = features[0].geometry;
//var theExtent = thePoly.getExtent().expand(2); //Zoom out slightly from the polygon's extent
//map.setExtent(theExtent);
});
}
};
this means that the html should be something like this
<input id="uniqueValuesSelect" data-dojo-type="dijit.form.ComboBox" value="statename" onchange="app.zoomRow(document.getElementById('uniqueValuesSelect').value, document.getElementById('uniqueValuesSelect2').value);" />
<input id="uniqueValuesSelect2" data-dojo-type="dijit.form.ComboBox" value="FarmedAcres" onchange="app.zoomRow(document.getElementById('uniqueValuesSelect').value, document.getElementById('uniqueValuesSelect2').value);" />
Add corresponding validations to stateId, acresId for avoiding null or undefined values

Hiding markers in googlemaps v3 in an object

i would like to hide markers in my object called lastCoordinates which isn't an array so when i click a button my markers hide and i can re-appear my markers with a different button. also in my code i have the function that when to right click a marker it gets deleted and the line snaps to the marker placed before the marker deleted this is done by using data from a separate random php file which creates random coordinates.
here is my html code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Simple markers</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
#panel {
position: absolute;
top: 5px;
left: 50%;
margin-left: -180px;
z-index: 5;
background-color: #fff;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
<script>
var map;
var stop = 0;
var markers = [];
window.onload=function ()
{
var myLatlng = new google.maps.LatLng(0,0);
var mapOptions = {
zoom: 2,
center: myLatlng
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
//google.maps.event.addDomListener(window, 'load', mapready);
getdata();
setInterval(function () {
if(stop<3000)
getdata();
stop++;
}, 2000);
}
function getdata()
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
//xmlhttp.open("GET","GetLocation.xml",true);
xmlhttp.open("GET","data.php",true);
xmlhttp.onreadystatechange=function () {gotdata()};
xmlhttp.send();
}
var lastCoordinates = [];
var polyline = new google.maps.Polyline({
strokeWeight: 6,
strokeColor:"#0000FF", // blue (RRGGBB, R=red, G=green, B=blue)
strokeOpacity: 1 // opacity of line
}); // create the polyline (global)
var path = []; // global variable to hold all the past locations
function gotdata(){
if (xmlhttp.readyState == 4){
var d = xmlhttp.responseXML.documentElement
//innerHTML shouldn't work for XML-Nodes
y = d.getElementsByTagName("y")[0].textContent,
x = d.getElementsByTagName("x")[0].textContent,
h = [x,y].join('_');
if(lastCoordinates[h]){
return;
}
lastCoordinates[h]= new google.maps.Marker({
position: new google.maps.LatLng(x,y),
map: map,
title: 'YAY'
});
rightclickableMarker(lastCoordinates[h],h);
path.push(lastCoordinates[h].getPosition());
drawPath();
}
}
function rightclickableMarker(marker, h) {
google.maps.event.addListener(marker, 'rightclick', function(evt) {
if(lastCoordinates[h] && lastCoordinates[h].setMap){
lastCoordinates[h].setMap(null);
delete marker;
var idx = path.indexOf(lastCoordinates[h].getPosition())
if (idx > -1) {
path.splice(idx, 1);
// removeLine();
drawPath();
}
}
});
}
function drawPath(){
polyline.setMap(map);
polyline.setPath(path);
}
function setAllMap(map) {
for (var i = 0; i < lastCoordinates.length; i++) {
lastCoordinates[i].setMap(map);
}
}
// Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
setAllMap(null);
}
// Shows any markers currently in the array.
function showMarkers() {
setAllMap(map);
}
</script>
</head>
<body>
<div id= "panel">
<input onclick="clearMarkers();" type=button value="Hide Markers">
<input onclick="showMarkers();" type=button value="Show All Markers">
</div>
<div id="map-canvas">
</div>
</body>
</html>
and my random php selector:
<?php
header("Content-type: application/xml");
?>
<Location>
<x><?php echo rand(-85,85); ?></x>
<y><?php echo rand(-85,85); ?></y>
</Location>
You cannot store your markers in lastCoordinates[h] and then expect to call them from var i=0 to i=lastCoordinates.length.....
function setAllMap(map) {
for (var i = 0; i < lastCoordinates.length; i++) {
lastCoordinates[i].setMap(map);
}
}
My suggestion, store all h values in another array
var h_s=[];
then do
for(var i = 0; i < h_s.length; i++){
lastCoordinates[h_s[i]].setMap(map);
}
Don't worry i figured out how to do it, what I needed to do was use the for in item to solve that problem
function rightclickableMarker(marker, h) {
google.maps.event.addListener(marker, 'rightclick', function(evt) {
if(lastCoordinates[h] && lastCoordinates[h].setMap){
lastCoordinates[h].setMap(null);
delete (lastCoordinates);
var idx = path.indexOf(lastCoordinates[h].getPosition())
if (idx > -1) {
path.splice(idx, 1);
// removeLine();
drawPath();
}
}
});
}
function drawPath(){
polyline.setMap(map);
polyline.setPath(path);
}
function setAllMap(map) {
for (var prop in lastCoordinates) {
lastCoordinates[prop].setMap(map); }
}

Google maps listener event acts like a click even though it is a mouseover

I am adding these two google.maps.event.addListener events
google.maps.event.addListener(markerAcademicCenter, "mouseover", function (e) {
markerIconAcademicCenter.url = 'MapIcons/Circle32.png'
});
google.maps.event.addListener(markerAcademicCenter, "mouseout", function (e) {
markerIconAcademicCenter.url = 'MapIcons/Circle64.png'
});
below this marker that already has a click event.
google.maps.event.addListener(markerAcademicCenter, "click", function (e) {
$(".campusMapInfoPanel > div").appendTo($(".InfoStorageDiv"));
$(".InfoPanelAcademicCenter").appendTo($(".campusMapInfoPanel"));
this.setZIndex(google.maps.Marker.MAX_ZINDEX + 1);
setZoomWhenMarkerClicked();
CampusMap.setCenter(markerAcademicCenter.getPosition());
});
The markerIconAcademicCenter.url is already set to Circle64 above these events. I expect the page to load with the larger circle — 64x64 — the switch back and forth as I hover and leave the marker area.
I'm having two problems with this
Nothing happens when I mouseover the marker, but it does happen when I click. On the initial click after the page loads, the map zooms and centers on the building and the marker image resizes. If I click on the building again, nothing else happens, but:
if I click on a menu link that triggers the click event, function buildingFocus(markerName) {google.maps.event.trigger(markerName, "click");} that function resets the icon as if it were the mouseout event.
To test this unexpected behavior further, I commented out each event one at a time. To clarify that something was actually happening, I first changed the initial image to clear.png.
When I took out the mouseover event, the image did not change when I clicked either the building event or the menu link as my first click after the page loaded. Before I removed the mouseover event, clicking on the menu as my second click after page load changed the icon to the mouseout image, but now clicking on the building causes this.
When I took out the mouseout event, clicking on the building as the first click made the icon change to the mouseover image, and clicking again on either area did nothing further. If I clicked on the menu link as the first or future clicks the image didn't change, but it did as soon as I clicked on the building.
When I took the click event out, the image never changed. By itself, the click event works as expected with both locations.
The icon of a marker is not an MVCObject, the API will not observe changes of the icon-properties.
You must modify the url of the icon and then call setIcon to apply the changes:
google.maps.event.addListener(markerAcademicCenter, "mouseover", function (e) {
var icon = this.getIcon();
icon.url = 'url/to/icon';
this.setIcon(icon);
});
But I wouldn't suggest it, when you use the icon for multiple markers changing the url(or other properties) will affect the original icon markerIconAcademicCenter (markers use a reference to the original object). You better create a copy with a modified url:
google.maps.event.addListener(markerAcademicCenter, "mouseover", function (e) {
var icon = this.getIcon(),copy={};
for(var k in icon){
copy[k]=icon[k];
}
copy.url= 'url/to/icon';
this.setIcon(copy);
});
Try using this :
google.maps.event.addListener(markerAcademicCenter, "mouseover", function (e) {
markerIconAcademicCenter.setIcon('url to icon');
});
instead of code below :
google.maps.event.addListener(markerAcademicCenter, "mouseover", function (e) {
markerIconAcademicCenter.url = 'MapIcons/Circle32.png'
});
This will sort out your problem of icon size change on mouseover and mouseout problem.
You can check the code below, so that you will be clear what I mean to say :
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: Map Simple</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?libraries=places"></script>
<script type="text/javascript">
var map, places, iw;
var markers = [];
var autocomplete;
var options = {
//types: ['(cities)'],
//componentRestrictions: {country: 'us'}
};
var geocoder = new google.maps.Geocoder();
function initialize() {
var myLatlng = new google.maps.LatLng(37.783259, -122.402708);
var myOptions = {
zoom: 12,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
places = new google.maps.places.PlacesService(map);
google.maps.event.addListener(map, 'tilesloaded', tilesLoaded);
autocomplete = new google.maps.places.Autocomplete(document.getElementById('autocomplete'), options);
google.maps.event.addListener(autocomplete, 'place_changed', function() {
showSelectedPlace();
});
}
function tilesLoaded() {
google.maps.event.clearListeners(map, 'tilesloaded');
google.maps.event.addListener(map, 'zoom_changed', search);
google.maps.event.addListener(map, 'dragend', search);
search();
}
function showSelectedPlace() {
clearResults();
clearMarkers();
var place = autocomplete.getPlace();
map.panTo(place.geometry.location);
markers[0] = new google.maps.Marker({
position: place.geometry.location,
map: map
});
iw = new google.maps.InfoWindow({
content: getIWContent(place)
});
iw.open(map, markers[0]);
search();
}
function search() {
var type;
for (var i = 0; i < document.controls.type.length; i++) {
if (document.controls.type[i].checked) {
type = document.controls.type[i].value;
}
}
autocomplete.setBounds(map.getBounds());
var search = {
bounds: map.getBounds()
};
if (type != 'establishment') {
search.types = [ type ];
}
places.search(search, function(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
clearResults();
clearMarkers();
for (var i = 0; i < 9; i++) {
markers[i] = new google.maps.Marker({
position: results[i].geometry.location,
animation: google.maps.Animation.DROP
});
google.maps.event.addListener(markers[i], 'mouseover', animate(i));
google.maps.event.addListener(markers[i], 'mouseout', reanimate(i));
google.maps.event.addListener(markers[i], 'click', getDetails(results[i], i));
setTimeout(dropMarker(i), i * 100);
//addResult(results[i], i);
mygetDetails(results[i], i);
}
}
})
}
function clearMarkers() {
for (var i = 0; i < markers.length; i++) {
if (markers[i]) {
markers[i].setMap(null);
markers[i] == null;
}
}
}
function dropMarker(i) {
return function() {
markers[i].setMap(map);
}
}
//Function to animate markers on there hover
function animate(locationCount){
return function(){
markers[locationCount].setIcon('https://mts.googleapis.com/vt/icon/name=icons/spotlight/spotlight-poi.png&scale=2');
$("#addressSpan"+locationCount).css('font-weight', '700');
$("#addressSpan"+locationCount).css('color', '#ff0000');
}
}
//Function to remove animation of markers on there hover
function reanimate(locationCount){
return function(){
markers[locationCount].setIcon('https://mts.googleapis.com/vt/icon/name=icons/spotlight/spotlight-poi.png&scale=1');
$("#addressSpan"+locationCount).css('font-weight', '');
$("#addressSpan"+locationCount).css('color', '');
}
}
function addResult(result, i) {
if(i<=9){
var results = document.getElementById("results");
var tr = document.createElement('tr');
tr.style.backgroundColor = (i% 2 == 0 ? '#F0F0F0' : '#FFFFFF');
tr.click = function() {
google.maps.event.trigger(markers[i], 'click');
};
var iconTd = document.createElement('td');
var nameTd = document.createElement('td');
var addressTd = document.createElement('td');
var icon = document.createElement('img');
icon.src = result.icon;
icon.setAttribute("class", "placeIcon");
icon.setAttribute("className", "placeIcon");
var name = document.createTextNode(result.name);
var address = document.createTextNode(result.formatted_address);
iconTd.appendChild(icon);
nameTd.appendChild(name);
addressTd.appendChild(address);
tr.appendChild(iconTd);
tr.appendChild(nameTd);
tr.appendChild(addressTd);
results.appendChild(tr);
}
}
function clearResults() {
var results = document.getElementById("results");
while (results.childNodes[0]) {
results.removeChild(results.childNodes[0]);
}
}
function clearResults1() {
var results = document.getElementById("results1");
while (results.childNodes[0]) {
results.removeChild(results.childNodes[0]);
}
}
function getDetails(result, i) {
return function() {
places.getDetails({
reference: result.reference
}, showInfoWindow(i));
}
}
function mygetDetails(result, i) {
return places.getDetails({
reference: result.reference
}, function(place, status){
if (status == google.maps.places.PlacesServiceStatus.OK) {
addResult(place, i);
}
});
}
function showInfoWindow(i) {
return function(place, status) {
if (iw) {
iw.close();
iw = null;
}
if (status == google.maps.places.PlacesServiceStatus.OK) {
iw = new google.maps.InfoWindow({
content: getIWContent(place)
});
iw.open(map, markers[i]);
}
}
}
function getIWContent(place) {
var content = "";
content += '<table><tr><td>';
content += '<img class="placeIcon" src="' + place.icon + '"/></td>';
content += '<td><b>' + place.name + '</b>';
content += '</td></tr></table>';
return content;
}
$(function(){
$("#autocomplete").keyup(function(){
clearResults1();
geocoder.geocode({"address": $(this).val()}, function(data, status) {
if (status == google.maps.GeocoderStatus.OK) {
$.each(data, function(int_index,value) {
var results = document.getElementById("results1");
var tr = document.createElement('tr');
tr.style.backgroundColor = (int_index% 2 == 0 ? '#F0F0F0' : '#FFFFFF');
var nameTd = document.createElement('td');
var name = document.createTextNode(value.formatted_address);
nameTd.appendChild(name);
tr.appendChild(nameTd);
results.appendChild(tr);
});
}
});
});
});
</script>
<style>
body {
font-family: sans-serif;
}
#map_canvas {
position: absolute;
width: 399px;
height: 399px;
top: 25px;
left: 0px;
border: 1px solid grey;
}
#listing {
position: absolute;
width: 200px;
height: 360px;
overflow: auto;
left: 401px;
top: 65px;
cursor: pointer;
}
#listing1 {
position: absolute;
width: 200px;
height: 360px;
overflow: auto;
left: 601px;
top: 65px;
cursor: pointer;
}
#controls {
width: 200px;
position: absolute;
top: 0px;
left: 400px;
height: 60px;
padding: 5px;
font-size: 12px;
}
.placeIcon {
width: 16px;
height: 16px;
margin: 2px;
}
#resultsTable, #resultsTable1{
font-size: 10px;
border-collapse: collapse;
}
#locationField {
width: 400px;
height: 25px;
top: 0px;
left: 0px;
position: absolute;
}
#autocomplete {
width: 400px;
}
</style>
</head>
<body style="margin:0px; padding:0px;" onLoad="initialize()">
<div id="locationField">
<input id="autocomplete" type="text" />
</div>
<div id="controls">
<form name="controls">
<input type="radio" name="type" value="establishment" onClick="search()" checked="checked"/>All<br/>
<input type="radio" name="type" value="restaurant" onClick="search()" />Restaurants<br/>
<input type="radio" name="type" value="lodging" onClick="search()" />Lodging
</form>
</div>
<div id="map_canvas"></div>
<div id="listing"><table id="resultsTable"><tr><td><h3>Suggested<br>Locations</h3></td></tr><tbody id="results"></tbody></table></div>
<div id="listing1"><table id="resultsTable1"><tr><td><h3>Suggested<br>Address</h3></td></tr><tbody id="results1"></tbody></table></div>
</body>
</html>
This is a working example.

Openlayers - display pacific markers popup using marker id and onclick event

I have the following code which addes 3 markers to the map along with there popup boxes what I want to do is have a list of location at bottom of page and using the id of the marker when click a place in the list it just make that places popup appear on the map.
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Open Street Map</title>
<style type="text/css">
body { font: normal 10pt Helvetica, Arial; }
#map { width: 100%; height: 100%; border: 0px; padding: 0px; }
</style>
<script src="lib/OpenLayers.js" type="text/javascript"></script>
<script type="text/javascript">
var iconSize = new OpenLayers.Size(21, 25);
var iconOffset = new OpenLayers.Pixel(-(iconSize.w / 2), -iconSize.h);
var icon = new OpenLayers.Icon("img/fourmarker.png",
iconSize, iconOffset);
var zoom, center, currentPopup, map, lyrMarkers;
var popupClass = OpenLayers.Class(OpenLayers.Popup.FramedCloud, {
"autoSize": true,
"minSize": new OpenLayers.Size(300, 50),
"maxSize": new OpenLayers.Size(500, 300),
"keepInMap": true
});
var bounds = new OpenLayers.Bounds();
function addMarker(id, lng, lat, info) {
var pt = new OpenLayers.LonLat(lng, lat)
.transform(new OpenLayers.Projection("EPSG:4326"),
map.getProjectionObject());
bounds.extend(pt);
var feature = new OpenLayers.Feature(lyrMarkers, pt);
feature.closeBox = true;
feature.popupClass = popupClass;
feature.data.popupContentHTML = info ;
feature.data.overflow = "auto";
var marker = new OpenLayers.Marker(pt, icon.clone());
var markerClick = function(evt) {
if (currentPopup != null && currentPopup.visible()) {
currentPopup.hide();
}
if (this.popup == null) {
this.popup = this.createPopup(this.closeBox);
map.addPopup(this.popup);
this.popup.show();
} else {
this.popup.toggle();
}
currentPopup = this.popup;
OpenLayers.Event.stop(evt);
};
marker.events.register("mousedown", feature, markerClick);
lyrMarkers.addMarker(marker);
}
function initMap() {
var options = {
projection: new OpenLayers.Projection("EPSG:900913"),
displayProjection: new OpenLayers.Projection("EPSG:4326"),
units: "m",
numZoomLevels: 19,
maxResolution: 156543.0339,
maxExtent: new OpenLayers.Bounds(-0.13011, -0.13011, 51.51039, 51.51039)
};
map = new OpenLayers.Map("map", options);
map.addControl(new OpenLayers.Control.DragPan());
var lyrOsm = new OpenLayers.Layer.OSM();
map.addLayer(lyrOsm);
lyrMarkers = new OpenLayers.Layer.Markers("Markers");
map.addLayer(lyrMarkers);
//add marker on given coordinates
addMarker('1',-0.12519,51.51112 , '<b>Tescos</b><br/>Covent garden');
addMarker('2',-0.13264,51.50918 , '<b>Spar</b><br/>Leicester Square');
addMarker('3', -0.12498,51.50807 , '<b>M & S</b><br/>Embankment');
center = bounds.getCenterLonLat();
map.setCenter(center, map.getZoomForExtent(bounds) - 1);
zoom = map.getZoom();
}
</script>
</head>
<body onload="initMap()" style="margin:0; border:0; padding:0; width:1000px; height:500px;">
<div id="map"></div>
</body>
</html>
EXTRA INFORMATION
I am going to add a list to bottom of map like so:
<ul>
<li>location1</li>
<li>location2</li>
<li>location3</li>
</ul>
What i want to get working is when the user clicks so location1 alink then that relevent popup box will show and the other will be removed.
How would this be done.
This very fast example (modify addMarker function):
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Open Street Map</title>
<style type="text/css">
body { font: normal 10pt Helvetica, Arial; }
#map { width: 100%; height: 100%; border: 0px; padding: 0px; }
#list > div { background-color: #aaa; margin-top: 10px; }
</style>
<script src="http://openlayers.org/api/OpenLayers.js" type="text/javascript"> </script>
</head>
<body onload="initMap()" style="margin:0; border:0; padding:0; width:1000px; height:500px;">
<div id="map"></div>
<div id="list" style="width:100%; height: 100%"></div>
</body>
<script type="text/javascript">
var iconSize = new OpenLayers.Size(21, 25);
var iconOffset = new OpenLayers.Pixel(-(iconSize.w / 2), -iconSize.h);
var icon = new OpenLayers.Icon("img/fourmarker.png",
iconSize, iconOffset);
var list = document.getElementById('list');
var zoom, center, currentPopup, map, lyrMarkers;
var popupClass = OpenLayers.Class(OpenLayers.Popup.FramedCloud, {
"autoSize": true,
"minSize": new OpenLayers.Size(300, 50),
"maxSize": new OpenLayers.Size(500, 300),
"keepInMap": true
});
var bounds = new OpenLayers.Bounds();
function addMarker(id, lng, lat, info) {
var pt = new OpenLayers.LonLat(lng, lat)
.transform(new OpenLayers.Projection("EPSG:4326"),
map.getProjectionObject());
bounds.extend(pt);
var feature = new OpenLayers.Feature(lyrMarkers, pt);
feature.closeBox = true;
feature.popupClass = popupClass;
feature.data.popupContentHTML = info ;
feature.data.overflow = "auto";
var marker = new OpenLayers.Marker(pt, icon.clone());
var markerClick = function(evt) {
if (currentPopup != null && currentPopup.visible()) {
currentPopup.hide();
}
if (this.popup == null) {
this.popup = this.createPopup(this.closeBox);
map.addPopup(this.popup);
this.popup.show();
} else {
this.popup.toggle();
}
currentPopup = this.popup;
OpenLayers.Event.stop(evt);
};
marker.events.register("mousedown", feature, markerClick);
lyrMarkers.addMarker(marker);
// add items
var listItem = OpenLayers.Util.createDiv(this.id, null, null, null, 'relative', null);
listItem.innerHTML = info;
list.appendChild(listItem);
var callback = function(e) {
marker.events.triggerEvent('mousedown');
console.log(marker);
OpenLayers.Event.stop(e);
};
OpenLayers.Event.observe(listItem, "touchend", OpenLayers.Function.bindAsEventListener(callback, this));
OpenLayers.Event.observe(listItem, "click", OpenLayers.Function.bindAsEventListener(callback, this));
}
function initMap() {
var options = {
projection: new OpenLayers.Projection("EPSG:900913"),
displayProjection: new OpenLayers.Projection("EPSG:4326"),
units: "m",
numZoomLevels: 19,
maxResolution: 156543.0339,
maxExtent: new OpenLayers.Bounds(-0.13011, -0.13011, 51.51039, 51.51039)
};
map = new OpenLayers.Map("map", options);
map.addControl(new OpenLayers.Control.DragPan());
var lyrOsm = new OpenLayers.Layer.OSM();
map.addLayer(lyrOsm);
lyrMarkers = new OpenLayers.Layer.Markers("Markers");
map.addLayer(lyrMarkers);
//add marker on given coordinates
addMarker('1',-0.12519,51.51112 , '<b>Tescos</b><br/>Covent garden');
addMarker('2',-0.13264,51.50918 , '<b>Spar</b><br/>Leicester Square');
addMarker('3', -0.12498,51.50807 , '<b>M & S</b><br/>Embankment');
center = bounds.getCenterLonLat();
map.setCenter(center, map.getZoomForExtent(bounds) - 1);
zoom = map.getZoom();
}
</script>
</html>

Categories

Resources