set start and end position in google roads API using javascript - 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>

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!

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

Google Maps API v3 - Directions with draggable alternate routes

I've successfully implemented google map direction service api : https://developers.google.com/maps/documentation/javascript/directions with 'draggble' option enabled. Is it possible to show all routes together if multiple routes are available between 2 locations?
The current code is similar to: https://developers.google.com/maps/documentation/javascript/examples/directions-draggable and I do have alternative routes available in response code as I've enabled provideRouteAlternatives: true.
I tried the solution provided in : How to display alternative route using google map api. But when I used that code, I found it draws multiple routes with independent markers. That is, if 4 routes are available, there will be 4 'A' locations and 4 'B' locations and while dragging - only one of them get selected. Please find the below screenshots.
Initial View:
After dragging initial locations (issue with duplicate locations)
I need to drag in such a way that, when the location A or B is dragged, there should not be any duplicates and alternate routes should be automatically shown.
My current code is as follows (API key not added here):
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Draggable directions</title>
<style>
#right-panel {
font-family: 'Roboto','sans-serif';
line-height: 30px;
padding-left: 10px;
}
#right-panel select, #right-panel input {
font-size: 15px;
}
#right-panel select {
width: 100%;
}
#right-panel i {
font-size: 12px;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
float: left;
width: 63%;
height: 100%;
}
#right-panel {
float: right;
width: 34%;
height: 100%;
}
.panel {
height: 100%;
overflow: auto;
}
</style>
</head>
<body>
<div id="map"></div>
<div id="right-panel">
<p>Total Distance: <span id="total"></span></p>
</div>
<script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {lat: -24.345, lng: 134.46} // Australia.
});
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer({
draggable: true,
map: map,
panel: document.getElementById('right-panel')
});
directionsDisplay.addListener('directions_changed', function() {
computeTotalDistance(directionsDisplay.getDirections());
});
displayRoute('Rosedale, MD, USA', 'Savage, MD, USA', directionsService,
directionsDisplay);
}
function displayRoute(origin, destination, service, display) {
service.route({
origin: origin,
destination: destination,
travelMode: 'DRIVING',
avoidTolls: true,
provideRouteAlternatives: true,
}, function(response, status) {
if (status === 'OK') {
for (var i = 0, len = response.routes.length; i < len; i++) {
new google.maps.DirectionsRenderer({
map: map,
directions: response,
routeIndex: i,
draggable : true,
});
}
display.setDirections(response);
} else {
alert('Could not display directions due to: ' + status);
}
});
}
function computeTotalDistance(result) {
var total = 0;
var myroute = result.routes[0];
for (var i = 0; i < myroute.legs.length; i++) {
total += myroute.legs[i].distance.value;
}
total = total / 1000;
document.getElementById('total').innerHTML = total + ' km';
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=API-KEY&callback=initMap">
</script>
</body>
</html>
Please help me. Thanks in advance!
Each route you draw is editable and has a start and end marker which means that you will always be dragging one of the routes marker and not all at once. You could use the suppressMarkers option to remove markers from the alternate routes but that wouldn't change a lot to the behavior.
The problem is that as each route is separate, if you move the start or end location, you should redraw every route otherwise only one will update.
That said, if you edit a route (other than by changing its start or end location) you should not redraw your routes. If you update the start or end location you will of course then lose any route waypoint you added. Unless you do something about that... which sounds like a pain.
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
var center = new google.maps.LatLng(0, 0);
var myOptions = {
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: center
}
map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
var start = "Sadulpur, India";
var end = "New Delhi, India";
plotDirections(start, end);
}
function plotDirections(start, end) {
var method = 'DRIVING';
var request = {
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode[method],
provideRouteAlternatives: true
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var routes = response.routes;
var colors = ['red', 'green', 'blue', 'orange', 'yellow', 'black'];
var directionsDisplays = [];
// Reset the start and end variables to the actual coordinates
start = response.routes[0].legs[0].start_location;
end = response.routes[0].legs[0].end_location;
// Loop through each route
for (var i = 0; i < routes.length; i++) {
var directionsDisplay = new google.maps.DirectionsRenderer({
map: map,
directions: response,
routeIndex: i,
draggable: true,
polylineOptions: {
strokeColor: colors[i],
strokeWeight: 4,
strokeOpacity: .3
}
});
// Push the current renderer to an array
directionsDisplays.push(directionsDisplay);
// Listen for the directions_changed event for each route
google.maps.event.addListener(directionsDisplay, 'directions_changed', (function(directionsDisplay, i) {
return function() {
var directions = directionsDisplay.getDirections();
var new_start = directions.routes[0].legs[0].start_location;
var new_end = directions.routes[0].legs[0].end_location;
if ((new_start.toString() !== start.toString()) || (new_end.toString() !== end.toString())) {
// Remove every route from map
for (var j = 0; j < directionsDisplays.length; j++) {
directionsDisplays[j].setMap(null);
}
// Redraw routes with new start/end coordinates
plotDirections(new_start, new_end);
}
}
})(directionsDisplay, i)); // End listener
} // End route loop
}
});
}
initialize();
#map-canvas {
height: 180px;
}
<div id="map-canvas"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
JSFiddle demo

How to add google map on WordPress

I have been working in this code, and works fine in localhost, but when I try to put this in word press the map doesn't come, and I don't know how to fix case I am new in WordPress.
A really need a hand on this, thanks
var geocoder;
function initMap() {
GeolocateUser();
var enderesso, Dest_location;
var UserLocation;
var markers = [];
var origin_place_id = null;
var destination_place_id = null;
var travel_mode = google.maps.TravelMode.DRIVING;
var map = new google.maps.Map(document.getElementById('map'), {
mapTypeControl: false,
zoom: 13
});
geocoder = new google.maps.Geocoder();
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer({
draggable: true,
map: map,
});
directionsDisplay.setMap(map);
var origin_input = document.getElementById('origin-input');
var destination_input = document.getElementById('destination-input');
var total_distance = document.getElementById('total-distance');
var total_duration = document.getElementById('total-duration');
map.controls[google.maps.ControlPosition.TOP_LEFT].push(origin_input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(destination_input);
var origin_autocomplete = new google.maps.places.Autocomplete(origin_input);
origin_autocomplete.bindTo('bounds', map);
var destination_autocomplete = new google.maps.places.Autocomplete(destination_input);
destination_autocomplete.bindTo('bounds', map);
// On Change route action
directionsDisplay.addListener('directions_changed', function(){
total_distance.value = getDistance(directionsDisplay.getDirections());
total_duration.value = getDuration(directionsDisplay.getDirections());
});
// On click map action
map.addListener('click',function(e){
clearMarkers();
if (!UserLocation) {
UserLocation=e.latLng;
addMarker(e.latLng);
route();
}else{
Dest_location=e.latLng;
route();
}
});
origin_autocomplete.addListener('place_changed', function() {
var place = origin_autocomplete.getPlace();
if (!place.geometry) {
window.alert("Autocomplete's returned place contains no geometry");
return;
}
clearMarkers();
expandViewportToFitPlace(map, place);
// If the place has a geometry, store its place ID and route if we have
// the other place ID
origin_place_id = place.place_id;
UserLocation = place.geometry.location;
addMarker(UserLocation);
route();
});
destination_autocomplete.addListener('place_changed', function() {
var place = destination_autocomplete.getPlace();
if (!place.geometry) {
window.alert("Autocomplete's returned place contains no geometry");
return;
}
expandViewportToFitPlace(map, place);
clearMarkers();
// If the place has a geometry, store its place ID and route if we have
// the other place ID
Dest_location = place.geometry.location;
destination_place_id = place.place_id;
route();
});
function route() {
if (!UserLocation || !Dest_location) {
return;
}
clearMarkers();
directionsService.route({
origin: UserLocation ,
destination: Dest_location,
travelMode: travel_mode
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
// Adds a marker to the map and push to the array.
function addMarker(location) {
var marker = new google.maps.Marker({
position:location,
map: map
});
markers.push(marker);
}
// Sets the map on all markers in the array.
function setMapOnAll(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
// Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
setMapOnAll(null);
}
// Deletes all markers in the array by removing references to them.
function deleteMarkers() {
clearMarkers();
markers = [];
}
//Get Distance
function getDistance(result){
var d = 0;
var myroute = result.routes[0];
for (var i = 0; i < myroute.legs.length; i++) {
d += myroute.legs[i].distance.value;
}
d=(d/1000);
return d;
}
//Get duration
function getDuration(result){
var time = 0;
var myroute = result.routes[0];
for (var i = 0; i < myroute.legs.length; i++) {
time += myroute.legs[i].duration.value;
}
time =(time/60)+10;
time = time.toFixed(0);
return time;
}
//Get full adress
function getAddress(latLng) {
var edress;
geocoder.geocode( {'latLng': latLng},
function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
if(results[0]) {
adress = results[0].formatted_address;
}
else {
adress = "No results";
}
}
else {
adress = status;
}
});
return adress;
}
//Geolocate User
function GeolocateUser(){
UserLocation = new google.maps.LatLng(0.0,0.0);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
UserLocation = new google.maps.LatLng(position.coords.latitude+0, position.coords.longitude+0);
addMarker(UserLocation);
map.setCenter(UserLocation);
});
}
}
//View Point Simple
function expandViewportToFitPlace(map, place) {
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(11);
}
}
}
<!DOCTYPE html>
<html>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
.controls {
margin-top: 10px;
border: 1px solid transparent;
border-radius: 2px 0 0 2px;
box-sizing: border-box;
-moz-box-sizing: border-box;
height: 32px;
outline: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}
#origin-input,
#destination-input {
background-color: #fff;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
margin-left: 12px;
padding: 0 11px 0 13px;
text-overflow: ellipsis;
width: 200px;
}
#origin-input:focus,
#destination-input:focus {
border-color: #4d90fe;
}
#mode-selector {
color: #fff;
background-color: #4d90fe;
margin-left: 12px;
padding: 5px 11px 0px 11px;
}
#mode-selector label {
font-family: Roboto;
font-size: 13px;
font-weight: 300;
}
</style>
<input id="origin-input" class="controls" type="text"
placeholder="Enter an origin location">
<input id="destination-input" class="controls" type="text"
>
<input type="text" id="total-distance" placeholder="Calculating.."/>
<input type="text" id="total-duration" placeholder="Calculating.."/>
<div id="map"></div>
<script src="main.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?signed_in=true&libraries=places&callback=initMap" async defer></script>
</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); }
}

Categories

Resources