Change mapbox on google maps - javascript

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!

Related

no api-key error massage

I have tried many ways and many places to enter the API key for but in all the cases, I get the error no-API-key. the request works fine in the postman, meaning the key works fine.
the places I tried:
where I mentioned in this code
at the end of snap to road request call
at the end of all the request calls
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Roads API Demo</title>
<style>
html, body, #map {
height: 100%;
margin: 0px;
padding: 0px
}
#panel {
position: absolute;
top: 5px;
left: 50%;
margin-left: -180px;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
}
#bar {
width: 240px;
background-color: rgba(255, 255, 255, 0.75);
margin: 8px;
padding: 4px;
border-radius: 4px;
}
#autoc {
width: 100%;
box-sizing: border-box;
}
</style>
<script src="/_static/js/jquery-bundle.js"></script>
<script
src="https://maps.googleapis.com/maps/api/js?libraries=drawing,places"></script>
<script>
var apiKey = 'I PUTTED THE KEY HERE IN THE LAST TRY';
var map;
var drawingManager;
var placeIdArray = [];
var polylines = [];
var snappedCoordinates = [];
function initialize() {
var mapOptions = {
zoom: 17,
center: {lat: -33.8667, lng: 151.1955}
};
map = new google.maps.Map(document.getElementById('map'), mapOptions);
// Adds a Places search box. Searching for a place will center the map on that
// location.
map.controls[google.maps.ControlPosition.RIGHT_TOP].push(
document.getElementById('bar'));
var autocomplete = new google.maps.places.Autocomplete(
document.getElementById('autoc'));
autocomplete.bindTo('bounds', map);
autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);
}
});
// Enables the polyline drawing control. Click on the map to start drawing a
// polyline. Each click will add a new vertice. Double-click to stop drawing.
drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYLINE,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [
google.maps.drawing.OverlayType.POLYLINE
]
},
polylineOptions: {
strokeColor: '#696969',
strokeWeight: 2
}
});
drawingManager.setMap(map);
// Snap-to-road when the polyline is completed.
drawingManager.addListener('polylinecomplete', function(poly) {
var path = poly.getPath();
polylines.push(poly);
placeIdArray = [];
runSnapToRoad(path);
});
// Clear button. Click to remove all polylines.
$('#clear').click(function(ev) {
for (var i = 0; i < polylines.length; ++i) {
polylines[i].setMap(null);
}
polylines = [];
ev.preventDefault();
return false;
});
}
// Snap a user-created polyline to roads and draw the snapped path
function runSnapToRoad(path) {
var pathValues = [];
for (var i = 0; i < path.getLength(); i++) {
pathValues.push(path.getAt(i).toUrlValue());
}
$.get('https://roads.googleapis.com/v1/snapToRoads', {
interpolate: true,
key: apiKey,
path: pathValues.join('|')
}, function(data) {
processSnapToRoadResponse(data);
drawSnappedPolyline();
getAndDrawSpeedLimits();
});
}
// Store snapped polyline returned by the snap-to-road service.
function processSnapToRoadResponse(data) {
snappedCoordinates = [];
placeIdArray = [];
for (var i = 0; i < data.snappedPoints.length; i++) {
var latlng = new google.maps.LatLng(
data.snappedPoints[i].location.latitude,
data.snappedPoints[i].location.longitude);
snappedCoordinates.push(latlng);
placeIdArray.push(data.snappedPoints[i].placeId);
}
}
// Draws the snapped polyline (after processing snap-to-road response).
function drawSnappedPolyline() {
var snappedPolyline = new google.maps.Polyline({
path: snappedCoordinates,
strokeColor: 'black',
strokeWeight: 3
});
snappedPolyline.setMap(map);
polylines.push(snappedPolyline);
}
// Gets speed limits (for 100 segments at a time) and draws a polyline
// color-coded by speed limit. Must be called after processing snap-to-road
// response.
function getAndDrawSpeedLimits() {
for (var i = 0; i <= placeIdArray.length / 100; i++) {
// Ensure that no query exceeds the max 100 placeID limit.
var start = i * 100;
var end = Math.min((i + 1) * 100 - 1, placeIdArray.length);
drawSpeedLimits(start, end);
}
}
// Gets speed limits for a 100-segment path and draws a polyline color-coded by
// speed limit. Must be called after processing snap-to-road response.
function drawSpeedLimits(start, end) {
var placeIdQuery = '';
for (var i = start; i < end; i++) {
placeIdQuery += '&placeId=' + placeIdArray[i];
}
$.get('https://roads.googleapis.com/v1/speedLimits',
'key=' + apiKey + placeIdQuery,
function(speedData) {
processSpeedLimitResponse(speedData, start);
}
);
}
// Draw a polyline segment (up to 100 road segments) color-coded by speed limit.
function processSpeedLimitResponse(speedData, start) {
var end = start + speedData.speedLimits.length;
for (var i = 0; i < speedData.speedLimits.length - 1; i++) {
var speedLimit = speedData.speedLimits[i].speedLimit;
var color = getColorForSpeed(speedLimit);
// Take two points for a single-segment polyline.
var coords = snappedCoordinates.slice(start + i, start + i + 2);
var snappedPolyline = new google.maps.Polyline({
path: coords,
strokeColor: color,
strokeWeight: 6
});
snappedPolyline.setMap(map);
polylines.push(snappedPolyline);
}
}
function getColorForSpeed(speed_kph) {
if (speed_kph <= 40) {
return 'purple';
}
if (speed_kph <= 50) {
return 'blue';
}
if (speed_kph <= 60) {
return 'green';
}
if (speed_kph <= 80) {
return 'yellow';
}
if (speed_kph <= 100) {
return 'orange';
}
return 'red';
}
$(window).load(initialize);
</script>
</head>
<body>
<div id="map"></div>
<div id="bar">
<p class="auto"><input type="text" id="autoc"/></p>
<p><a id="clear" href="#">Click here</a> to clear map.</p>
</div>
</body>
</html>
In the script that loads the JS api
<script src="https://maps.googleapis.com/maps/api/js?libraries=drawing,places&key=your_api_key"></script>
and for Web Services
https://roads.googleapis.com/v1/speedLimits?parameters&key=YOUR_API_KEY

Leaflet Markers + clustering terribly slow, jsfiddle demo(200-400 markers)

here is my script, I'm currently having a bad time with leaflet, it is taking substantial amounts of time to load my markers yet I'm only playing with up to 200-500 at a time and can't seem to find the reason why.
Markers are pulled from an API and stored into an array then plotted onto the map upon clicking a section on the map, see for yourself on the live demo, it works fine until loading markers then it starts to lag a lot when zooming
If anybody has a solution for me it would be much appreciated as I intend to have a lot more markers than it is currently pulling.
var postcode;
var police_api_dates = [
"&date=2017-03",
];
var completed_requests = 0;
var police_api_base_url = "https://data.police.uk/api/crimes-street/all-crime?poly=";
var crimes = [];
var count = 0;
var mymap = L.map('map').setView([53.7983587, -1.6191674], 11);
mymap.createPane('labels');
mymap.getPane('labels').style.zIndex = 650;
mymap.getPane('labels').style.pointerEvents = 'none';
var positron = L.tileLayer('http://{s}.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}.png', {
attribution: '©OpenStreetMap, ©CartoDB'
}).addTo(mymap);
var positronLabels = L.tileLayer('http://{s}.basemaps.cartocdn.com/light_only_labels/{z}/{x}/{y}.png', {
attribution: '©OpenStreetMap, ©CartoDB',
pane: 'labels'
}).addTo(mymap);
L.tileLayer('https://api.mapbox.com/styles/v1/adam97x/cjavcj1680vgz2sqshn70q5pg/tiles/256/{z}/{x}/{y}?access_token=pk.eyJ1IjoiYWRhbTk3eCIsImEiOiJjamF2Y2k1NmswYzhuMnZtazlpNXU2NDExIn0.RifBBI5nelL-4d21mkn7Wg', {
maxZoom: 18,
attribution: 'Map data © OpenStreetMap contributors, ' +
'CC-BY-SA, ' +
'Imagery © Mapbox',
id: 'mapbox.streets'
}).addTo(mymap);
// control that shows state info on hover
var info = L.control();
info.onAdd = function (mymap) {
this._div = L.DomUtil.create('div', 'info');
this.update();
return this._div;
};
info.update = function (properties) {
this._div.innerHTML = '<h4>Highlighted Postcode</h4>' + (properties ?
'<b> Postcode: ' + properties.Name
: 'Hover over a state');
};
info.addTo(mymap);
function style(feature) {
return {
fillColor: 'grey',
weight: 2,
opacity: 1,
color: 'white',
dashArray: '3',
fillOpacity: 0.5
};
}
L.geoJson(statesdata, {style: style}).addTo(mymap);
function highlightFeature(e) {
var layer = e.target;
layer.setStyle({
weight: 5,
opacity: 1,
color: '#000',
dashArray: '',
fillOpacity: 0.7
});
if (!L.Browser.ie && !L.Browser.opera && !L.Browser.edge) {
layer.bringToFront();
}
info.update(layer.feature.properties);
postcode = layer.feature.properties.Name.substr(2)-1;
console.log(postcode);
}
/*global statesdata*/
var geojson;
function resetHighlight(e) {
geojson.resetStyle(e.target);
info.update();
}
function zoomFeature(e) {
mymap.fitBounds(e.target.getBounds());
var colonString = statesdata
.features[postcode]
.geometry
.coordinates[0]
.map(pair => pair.reverse().join())
.join(':');
for (var a = 0; a < 1; a++){
var request = police_api_base_url + colonString + police_api_dates[a]
get_JSON(request, JSON_callback);
}
}
function onEachFeature(feature, layer) {
layer.on({
mouseover: highlightFeature,
mouseout: resetHighlight,
click: zoomFeature
});
}
geojson = L.geoJson(statesdata, {
style: style,
onEachFeature: onEachFeature
}).addTo(mymap);
geojson.eachLayer(function (layer) {
layer.bindPopup(layer.feature.properties.Name);
});
function JSON_callback(data){
completed_requests++;
var data_len = data.length;
if (data[0] != undefined){
for (var i = 0; i < data_len; i++){
cat = data[i]["category"];
lat = data[i]["location"]["latitude"];
lng = data[i]["location"]["longitude"];
if (cat in crimes) {
crimes[cat]++;
} else {
crimes[cat] = 1;
}
create_marker(lat, lng);
}
}
if (completed_requests == 1){
console.log("Requests done");
console.log(crimes);
}
}
function create_crime_markers(lat, lng, cat){
show_by_id("num_of_crimes_load_img");
show_by_id("popular_crime_load_img");
completed_requests = 0;
num_of_crimes = 0;
crimes = {};;
for (var a = 0; a < 1; a++){
var request = police_api_base_url + lat + "&lng=" + lng + police_api_dates[a]
get_JSON(request, JSON_callback);
}
}
var current_lat_lng = [];
function create_marker(lat, lng, title){
current_lat_lng.push(lat, lng, cat);
chunksize = 3;
var chunks = [];
current_lat_lng.forEach((item)=>{
if(!chunks.length || chunks[chunks.length-1].length == chunksize)
chunks.push([]);
chunks[chunks.length-1].push(item);
});
var markers = L.markerClusterGroup({
chunkedloading: true,
spiderfyOnMaxZoom: true,
showCoverageOnHover: false,
zoomToBoundsOnClick: true,
spiderfyDistanceMultiplier: 2.4
});
var markerList = [];
for (var f = 0; f < chunks.length; f++) {
var marker = new L.circleMarker([chunks[f][0],chunks[f][1]])
markerList.push(marker);
}
markers.addLayers(markerList);
mymap.addLayer(markers);
}
body { margin:0; padding:0; }
#map { position:absolute; top:0; bottom:0; width:100%; }
.info { padding: 6px 8px; font: 14px/16px Arial, Helvetica, sans-serif; background: white; background: rgba(255,255,255,0.8); box-shadow: 0 0 15px rgba(0,0,0,0.2); border-radius: 5px; } .info h4 { margin: 0 0 5px; color: #777; }
<html>
<head>
<meta charset=utf-8 />
<title>KML Data</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.2.0/dist/leaflet.css" />
<link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster#1.2.0/dist/MarkerCluster.Default.css" />
<script src="https://unpkg.com/leaflet#1.2.0/dist/leaflet.js"></script>
<script type="text/javascript" src="https://project-adam97.c9users.io/asset/bd.js"></script>
<script src="https://project-adam97.c9users.io/asset/requests.js"></script>
</head>
<body>
<script> src='https://api.mapbox.com/mapbox.js/plugins/leaflet-omnivore/v0.2.0/leaflet-omnivore.min.js'></script>
<script src="https://unpkg.com/leaflet.markercluster#1.2.0/dist/leaflet.markercluster.js"></script>
<div id='map'></div>
</body>
</html>

set start and end position in google roads API using javascript

I want to know if setting start and end location in the map while I'm retrieving coordinates and placeId through google roads API is possible or not? Because while I initialize Roads API by setting a custom coordinate like:
var mapOptions = {
zoom: 17,
center: {lat: -33.8667, lng: 151.1955}
};
its shows me a specific location in the map where the coordinate exists. But I want to initialize a map where I set a start and end location in the map and then start to use snapToRoads API to retrieve coordinates.
Ok, I have done a little bit digging and solved it by myself.
The Javascript Part:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=drawing,places"></script>
<!--Elevation JS
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>-->
<script>
//GOOGLE_API_KEY
var apiKey = 'GOOGLE_API_KEY';
alert("Provide GOOGLE API KEY");
var map;
var elevator;
var directionsDisplay;
var directionsService;
var drawingManager;
var placeIdArray = [];
var polylines = [];
var snappedCoordinates = [];
var initialLocation;
var siberia = new google.maps.LatLng(60, 105);
var newyork = new google.maps.LatLng(40.69847032728747, -73.9514422416687);
var browserSupportFlag = new Boolean();
function initialize()
{
var mapOptions = {
zoom: 17,
center: {lat: -33.8667, lng: 151.1955}
};
directionsService = new google.maps.DirectionsService();
var polylineOptionsActual = new google.maps.Polyline({
strokeColor: '#FF0000',
strokeOpacity: 0.6,
strokeWeight: 2
});
directionsDisplay = new google.maps.DirectionsRenderer({polylineOptions: polylineOptionsActual});
map = new google.maps.Map(document.getElementById('map'), mapOptions);
directionsDisplay.setMap(map);
// Create an ElevationService
elevator = new google.maps.ElevationService();
// Adds a Places search box. Searching for a place will center the map on that
// location.
map.controls[google.maps.ControlPosition.RIGHT_TOP].push(
document.getElementById('bar'));
var autocomplete = new google.maps.places.Autocomplete(document.getElementById('autocStart'));
autocomplete.bindTo('bounds', map);
autocomplete.addListener('place_changed', function() {
var placeStart = autocomplete.getPlace();
//alert(placeStart.place_id);
document.getElementById("startPlaceId").value=placeStart.place_id;
});
var autocomplete1 = new google.maps.places.Autocomplete(document.getElementById('autocEnd'));
autocomplete1.bindTo('bounds', map);
autocomplete1.addListener('place_changed', function() {
var placeEnd = autocomplete1.getPlace();
//alert(placeEnd.place_id);
document.getElementById("endPlaceId").value=placeEnd.place_id;
});
// Enables the polyline drawing control. Click on the map to start drawing a
// polyline. Each click will add a new vertice. Double-click to stop drawing.
drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYLINE,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [
google.maps.drawing.OverlayType.POLYLINE
]
},
polylineOptions: {
strokeColor: '#696969',
strokeWeight: 2
}
});
drawingManager.setMap(map);
// Snap-to-road when the polyline is completed.
drawingManager.addListener('polylinecomplete', function(poly) {
var path = poly.getPath();
polylines.push(poly);
placeIdArray = [];
runSnapToRoad(path);
});
// Clear button. Click to remove all polylines.
$('#clear').click(function(ev) {
for (var i = 0; i < polylines.length; ++i) {
polylines[i].setMap(null);
}
polylines = [];
ev.preventDefault();
return false;
});
}
// Snap a user-created polyline to roads and draw the snapped path
function runSnapToRoad(path) {
var pathValues = [];
for (var i = 0; i < path.getLength(); i++) {
pathValues.push(path.getAt(i).toUrlValue());
}
$.get('https://roads.googleapis.com/v1/snapToRoads', {
interpolate: true,
key: apiKey,
path: pathValues.join('|')
}, function(data) {
processSnapToRoadResponse(data);
drawSnappedPolyline();
//getAndDrawSpeedLimits();
});
}
// Store snapped polyline returned by the snap-to-road method.
function processSnapToRoadResponse(data)
{
snappedCoordinates = [];
placeIdArray = [];
for (var i = 0; i < data.snappedPoints.length; i++)
{
var latlng = new google.maps.LatLng(
data.snappedPoints[i].location.latitude,
data.snappedPoints[i].location.longitude);
//getElevation(latlng);
snappedCoordinates.push(latlng);
placeIdArray.push(data.snappedPoints[i].placeId);
}
//get Altitude in meters
getElevation(snappedCoordinates);
document.getElementById("snappedCoordinatesArray").value=snappedCoordinates;
document.getElementById("snappedPaceIdArray").value=placeIdArray;
}
// Draws the snapped polyline (after processing snap-to-road response).
function drawSnappedPolyline() {
var snappedPolyline = new google.maps.Polyline({
path: snappedCoordinates,
strokeColor: 'black',
strokeWeight: 3
});
snappedPolyline.setMap(map);
polylines.push(snappedPolyline);
}
// Gets speed limits (for 100 segments at a time) and draws a polyline
// color-coded by speed limit. Must be called after processing snap-to-road
// response.
function getAndDrawSpeedLimits() {
for (var i = 0; i <= placeIdArray.length / 100; i++) {
// Ensure that no query exceeds the max 100 placeID limit.
var start = i * 100;
var end = Math.min((i + 1) * 100 - 1, placeIdArray.length);
drawSpeedLimits(start, end);
}
}
// Gets speed limits for a 100-segment path and draws a polyline color-coded by
// speed limit. Must be called after processing snap-to-road response.
function drawSpeedLimits(start, end) {
var placeIdQuery = '';
for (var i = start; i < end; i++) {
placeIdQuery += '&placeId=' + placeIdArray[i];
}
$.get('https://roads.googleapis.com/v1/speedLimits',
'key=' + apiKey + placeIdQuery,
function(speedData) {
processSpeedLimitResponse(speedData, start);
}
);
}
// Draw a polyline segment (up to 100 road segments) color-coded by speed limit.
function processSpeedLimitResponse(speedData, start) {
var end = start + speedData.speedLimits.length;
for (var i = 0; i < speedData.speedLimits.length - 1; i++) {
var speedLimit = speedData.speedLimits[i].speedLimit;
var color = getColorForSpeed(speedLimit);
// Take two points for a single-segment polyline.
var coords = snappedCoordinates.slice(start + i, start + i + 2);
var snappedPolyline = new google.maps.Polyline({
path: coords,
strokeColor: color,
strokeWeight: 6
});
snappedPolyline.setMap(map);
polylines.push(snappedPolyline);
//passDataToObjC();
}
}
function getColorForSpeed(speed_kph) {
if (speed_kph <= 40) {
return 'purple';
}
if (speed_kph <= 50) {
return 'blue';
}
if (speed_kph <= 60) {
return 'green';
}
if (speed_kph <= 80) {
return 'yellow';
}
if (speed_kph <= 100) {
return 'orange';
}
return 'red';
}
function getElevation(snappedCoordinatesArr)
{
var locations = [];
// Retrieve the latlng and push it on the array
for (var i = 0; i < snappedCoordinatesArr.length; i++)
{
locations.push(snappedCoordinatesArr[i]);
}
// Create a LocationElevationRequest object using the array's one value
var positionalRequest =
{
'locations': locations
}
//alert(positionalRequest);
// Initiate the location request
elevator.getElevationForLocations(positionalRequest, function(results, status)
{
if (status == google.maps.ElevationStatus.OK)
{
// Retrieve the first result
if (results)
{
var altitudeArr=[];
for(var j=0;j<results.length;j++)
{
altitudeArr.push(results[j].elevation);
}
document.getElementById("altitudeArray").value=altitudeArr;
document.getElementById("dataDisplay").style.display="block";
//alert(altitudeArr);
}
else
{
alert('No results found');
}
}
else
{
alert('Elevation service failed due to: ' + status);
}
});
}
function calcRoute()
{
var start = document.getElementById("autocStart").value;
var end = document.getElementById('autocEnd').value;
//alert(start);
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
$(window).load(initialize);
</script>
And The HTML:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Roads API</title>
<style>
html, body, #map {
height: 100%;
margin: 0px;
padding: 0px
}
#panel {
position: absolute;
top: 5px;
left: 50%;
margin-left: -180px;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
}
#bar {
width: 240px;
background-color: rgba(255, 255, 255, 0.75);
margin: 8px;
padding: 4px;
border-radius: 4px;
}
#autoc {
width: 98%;
box-sizing: border-box;
}
</style>
<body>
<div id="map"></div>
<div id="bar">
<form id="geodata-form" action="http://wayzme.sulavmart.com/map/savedata">
<div id="dataDisplay" style="display:none;">
CoordinatesArray:
<input type="text" id="snappedCoordinatesArray" />
AltitudeArray:
<input type="text" id="altitudeArray" />
PaceIdArray:
<input type="text" id="snappedPaceIdArray" />
<input type="hidden" id="startPlaceId" />
<input type="hidden" id="endPlaceId" />
</div>
<p class="auto">
<input type="text" id="autocStart" style="width:98% !important" name="start" />
</p>
<p class="auto">
<input type="text" id="autocEnd" style="width:98% !important" name="end"/>
</p>
<input type="button" value="Get Directions" onClick="calcRoute();">
</form>
<p><a id="clear" href="#">Click here</a> to clear map.</p>
</div>
</body>
</html>

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); }
}

issue with click event in nokia maps api

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>

Categories

Resources