Broken Route & Unclickable Locations on Embedded Map - google-maps
The route found on the embedded google map at the URL below is broken and I would like it to be continuous.
The locations found on the same map are unclickable and I would like them to be clickable.
Map here: https://www.theafricamonth.com/trail1-1 or code below.
Would greatly appreciate someone to shed some knowledge on this. Thanks in advance.
<script src="//maps.googleapis.com/maps/api/js?key=AIzaSyDTIfL5nxelK1h8HKkrUDkMn1emcLh-S4I&extension=.js"></script>
<script src="//cdn.mapkit.io/v1/infobox.js"></script>
<link href="//fonts.googleapis.com/css?family=Roboto:300,400" rel="stylesheet">
<link href="//cdn.mapkit.io/v1/infobox.css" rel="stylesheet" >
<script>
google.maps.event.addDomListener(window, 'load', init);
var map, markersArray = [];
function bindInfoWindow(marker, map, location) {
google.maps.event.addListener(marker, 'click', function() {
function close(location) {
location.ib.close();
location.infoWindowVisible = false;
location.ib = null;
}
if (location.infoWindowVisible === true) {
close(location);
} else {
markersArray.forEach(function(loc, index) {
if (loc.ib && loc.ib !== null) {
close(loc);
}
});
var boxText = document.createElement('div');
boxText.style.cssText = 'background: #fff;';
boxText.classList.add('md-whiteframe-2dp');
function buildPieces(location, el, part, icon) {
if (location[part] === '') {
return '';
} else if (location.iw[part]) {
switch (el) {
case 'photo':
if (location.photo) {
return '<div class="iw-photo" style="background-image: url(' + location.photo + ');"></div>';
} else {
return '';
}
break;
case 'iw-toolbar':
return '<div class="iw-toolbar"><h3 class="md-subhead">' + location.title + '</h3></div>';
break;
case 'div':
switch (part) {
case 'email':
return '<div class="iw-details"><i class="material-icons" style="color:#4285f4;"><img src="//cdn.mapkit.io/v1/icons/' + icon + '.svg"/></i><span>' + location.email + '</span></div>'
break;
case 'web':
return '<div class="iw-details"><i class="material-icons" style="color:#4285f4;"><img src="//cdn.mapkit.io/v1/icons/' + icon + '.svg"/></i><span>' + location.web_formatted + '</span></div>';
break;
case 'desc':
return '<label class="iw-desc" for="cb_details"><input type="checkbox" id="cb_details"/><h3 class="iw-x-details">Details</h3><i class="material-icons toggle-open-details"><img src="//cdn.mapkit.io/v1/icons/' + icon + '.svg"/></i><p class="iw-x-details">' + location.desc + '</p></label>';
break;
default:
return '<div class="iw-details"><i class="material-icons"><img src="//cdn.mapkit.io/v1/icons/' + icon + '.svg"/></i><span>' + location.part + '</span></div>';
break;
}
break;
case 'open_hours':
var items = '';
if (location.open_hours.length > 0) {
for (var i = 0; i < location.open_hours.length; ++i) {
if (i !== 0) {
items += '<li><strong>' + location.open_hours[i].day + '</strong><strong>' + location.open_hours[i].hours + '</strong></li>';
}
var first = '<li><label for="cb_hours"><input type="checkbox" id="cb_hours"/><strong>location.open_hours[0].day</strong><strong>' + location.open_hours[0].hours + '</strong><i class="material-icons toggle-open-hours"><img src="//cdn.mapkit.io/v1/icons/keyboard_arrow_down.svg"/></i><ul>' + items + '</ul></label></li>';
}
return '<div class="iw-list"><i class="material-icons first-material-icons" style="color:#4285f4;"><img src="//cdn.mapkit.io/v1/icons/' + icon + '.svg"/></i><ul>' + first + '</ul></div>';
} else {
return '';
}
break;
}
} else {
return '';
}
}
boxText.innerHTML = buildPieces(location, 'photo', 'photo', '') + buildPieces(location, 'iw-toolbar', 'title', '') + buildPieces(location, 'div', 'address', 'location_on') + buildPieces(location, 'div', 'web', 'public') + buildPieces(location, 'div', 'email', 'email') + buildPieces(location, 'div', 'tel', 'phone') + buildPieces(location, 'div', 'int_tel', 'phone') + buildPieces(location, 'open_hours', 'open_hours', 'access_time') + buildPieces(location, 'div', 'desc', 'keyboard_arrow_down');
var myOptions = {
alignBottom: true,
content: boxText,
disableAutoPan: true,
maxWidth: 0,
pixelOffset: new google.maps.Size(-140, -40),
zIndex: null,
boxStyle: {
opacity: 1,
width: '280px'
},
closeBoxMargin: '0px 0px 0px 0px',
infoBoxClearance: new google.maps.Size(1, 1),
isHidden: false,
pane: 'floatPane',
enableEventPropagation: false
};
location.ib = new InfoBox(myOptions);
location.ib.open(map, marker);
location.infoWindowVisible = true;
}
});
}
function init() {
var mapOptions = {
center: new google.maps.LatLng(-28.12333312723434, 23.738126687499967),
zoom: 5,gestureHandling: 'auto',fullscreenControl: false,zoomControl: true,
disableDoubleClickZoom: false,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
},
scaleControl: true,
scrollwheel: true,
streetViewControl: false,
draggable: true,
clickableIcons: true,
fullscreenControlOptions: {
position: google.maps.ControlPosition.TOP_RIGHT
},
zoomControlOptions: {
position: google.maps.ControlPosition.RIGHT_BOTTOM
},
streetViewControlOptions: {
position: google.maps.ControlPosition.RIGHT_BOTTOM
},
mapTypeControlOptions: {
position: google.maps.ControlPosition.TOP_LEFT
},
mapTypeId: google.maps.MapTypeId.ROADMAP,
styles: [{"featureType":"landscape","stylers":[{"hue":"#FFAD00"},{"saturation":50.2},{"lightness":-34.8},{"gamma":1}]},{"featureType":"road.highway","stylers":[{"hue":"#FFAD00"},{"saturation":-19.8},{"lightness":-1.8},{"gamma":1}]},{"featureType":"road.arterial","stylers":[{"hue":"#FFAD00"},{"saturation":72.4},{"lightness":-32.6},{"gamma":1}]},{"featureType":"road.local","stylers":[{"hue":"#FFAD00"},{"saturation":74.4},{"lightness":-18},{"gamma":1}]},{"featureType":"water","stylers":[{"hue":"#00FFA6"},{"saturation":-63.2},{"lightness":38},{"gamma":1}]},{"featureType":"poi","stylers":[{"hue":"#FFC300"},{"saturation":54.2},{"lightness":-14.4},{"gamma":1}]}]
}
var mapElement = document.getElementById('mapkit-6386');
var map = new google.maps.Map(mapElement, mapOptions);
var locations = [{"title":"Cape Town","address":"Cape Town, South Africa","tel":"","int_tel":"","email":"","web":"","web_formatted":"","open":"","time":"","lat":-33.9248685,"lng":18.424055299999964,"photo":"","vicinity":"Cape Town","open_hours":"","marker":{"fillColor":"#F44336","fillOpacity":1,"strokeWeight":0,"scale":1.5,"anchor":{"x":10,"y":30},"origin":{"x":0,"y":0},"style":5},"iw":{"address":true,"desc":true,"email":true,"enable":true,"int_tel":true,"open":true,"open_hours":true,"photo":true,"tel":true,"title":true,"web":true}},{"title":"Stellenbosch","address":"Stellenbosch, South Africa","tel":"","int_tel":"","email":"","web":"","web_formatted":"","open":"","time":"","lat":-33.9321045,"lng":18.86015199999997,"photo":"","vicinity":"Stellenbosch","open_hours":"","marker":{"fillColor":"#F44336","fillOpacity":1,"strokeWeight":0,"scale":1.5,"anchor":{"x":10,"y":30},"origin":{"x":0,"y":0},"style":5},"iw":{"address":true,"desc":true,"email":true,"enable":true,"int_tel":true,"open":true,"open_hours":true,"photo":true,"tel":true,"title":true,"web":true}},{"title":"Wilderness","address":"Wilderness, South Africa","desc":"","tel":"","int_tel":"","email":"","web":"","web_formatted":"","open":"","time":"","lat":-33.9940082,"lng":22.574848100000054,"vicinity":"Wilderness","marker":"","iw":{"address":true,"desc":true,"email":true,"enable":true,"int_tel":true,"open":true,"open_hours":true,"photo":true,"tel":true,"title":true,"web":true}},{"title":"Port Elizabeth","address":"Port Elizabeth, South Africa","desc":"","tel":"","int_tel":"","email":"","web":"","web_formatted":"","open":"","time":"","lat":-33.9608369,"lng":25.602242299999943,"vicinity":"Port Elizabeth","marker":"","iw":{"address":true,"desc":true,"email":true,"enable":true,"int_tel":true,"open":true,"open_hours":true,"photo":true,"tel":true,"title":true,"web":true}},{"title":"Two Rivers Rest Camp","address":"Botswana","desc":"","tel":"","int_tel":"","email":"","web":"","web_formatted":"","open":"","time":"","lat":-26.4715622,"lng":20.6237251,"vicinity":"Botswana","marker":"","iw":{"address":true,"desc":true,"email":true,"enable":true,"int_tel":true,"open":true,"open_hours":true,"photo":true,"tel":true,"title":true,"web":true}},{"title":"Orange River Lodge","address":"South Namibia, Namibia, Noordoewer, Namibia","desc":"","tel":"063 297 012","int_tel":"+264 63 297 012","email":"","web":"http://www.orangeriverlodge.com/","web_formatted":"orangeriverlodge.com","open":"","time":"","lat":-28.74396,"lng":17.616750000000025,"vicinity":"South Namibia, Namibia","marker":"","iw":{"address":true,"desc":true,"email":true,"enable":true,"int_tel":true,"open":true,"open_hours":true,"photo":true,"tel":true,"title":true,"web":true}},{"title":"Windhoek","address":"Windhoek, Namibia","desc":"","tel":"","int_tel":"","email":"","web":"","web_formatted":"","open":"","time":"","lat":-22.5608807,"lng":17.0657549,"vicinity":"Windhoek","marker":"","iw":{"address":true,"desc":true,"email":true,"enable":true,"int_tel":true,"open":true,"open_hours":true,"photo":true,"tel":true,"title":true,"web":true}}];
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
icon: locations[i].marker,
position: new google.maps.LatLng(locations[i].lat, locations[i].lng),
map: map,
title: locations[i].title,
address: locations[i].address,
desc: locations[i].desc,
tel: locations[i].tel,
int_tel: locations[i].int_tel,
vicinity: locations[i].vicinity,
open: locations[i].open,
open_hours: locations[i].open_hours,
photo: locations[i].photo,
time: locations[i].time,
email: locations[i].email,
web: locations[i].web,
iw: locations[i].iw
});
markersArray.push(marker);
if (locations[i].iw.enable === true){
bindInfoWindow(marker, map, locations[i]);
}
}
arrays = [];
while (locations.length > 0) {
arrays.push(locations.splice(0, 5));
}
for (var i = 0; i < arrays.length; i++) {
makeRoutes(arrays[i]);
}
function makeRoutes(locations) {
var waypts = [];
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer({
suppressMarkers: true,
preserveViewport: true
});
if (locations.length > 1){
for (var i = 0; i < locations.length; i++) {
waypts.push({
location:new google.maps.LatLng(locations[i].lat, locations[i].lng),
stopover:true
});
}
}
var request = {
origin: new google.maps.LatLng(locations[0].lat, locations[0].lng),
destination: new google.maps.LatLng(locations[locations.length - 1].lat, locations[locations.length - 1].lng),
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
polylineOptions = {
strokeColor: '#80b8ea',
strokeWeight: '6'
}
directionsDisplay.setOptions({
polylineOptions: polylineOptions
});
directionsDisplay.setDirections(response);
}
});
directionsDisplay.setMap(map);
}
}
</script>
<style>
#mapkit-6386 {
height: 400px;
width: 900px;
max-width: 100%;
}
</style>
<div id="mapkit-6386"></div>
Your route is "broken" because that is what your code does. It calls makeRoutes(arrays[i]); where arrays is your locations array split into two pieces.
The markers aren't clickable because the of the following error in the javascript console: Uncaught ReferenceError: InfoBox is not defined because that file (//cdn.mapkit.io/v1/infobox.js) has a syntax error:
Uncaught SyntaxError: Unexpected token export infobox.js:88
And the code that populates the infowindow doesn't work.
proof of concept fiddle
Related
Head-office to Branch-office Google Map with Marker in java-script
i have to mark the head-office to branch office with poly-line, below code work only for branch office, not marked for head-office to branch-office. ex:- head-office may be -- Delhi, branch office -- Chennai, Mumbai, Bangalore my code working for branch office only, i would like show head-office to each branch office to marked with Poly-line can anybody share good idea to solve... code:- $(function () { start(); }); function start() { var markers = [ {HOLat:13.089562900000,HOLng:80.290230500000,DeLat:12.990928000000, DeLng: 80.242616500000}, {HOLat:13.089562900000,HOLng:80.290230500000,DeLat:12.991269800000, DeLng: 80.242545000000}, {HOLat:13.089562900000,HOLng:80.290230500000,DeLat:12.991316800000, DeLng: 80.242520000000} ] if (!isEmpty(markers)) { var mapOptions = { center: new google.maps.LatLng(markers[0].HOLat, markers[0].HOLng), zoom: 12, mapTypeId: google.maps.MapTypeId.ROADMAP }; var infoWindow = new google.maps.InfoWindow(); var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions); var start = ''; var points = []; for (i = 0; i < markers.length; i++) { img = "icons/" + (i+1) + ".png"; var data = markers[i]; myLatlng = new google.maps.LatLng(data.DeLat, data.DeLng); points.push(new google.maps.LatLng(data.DeLat, data.DeLng)); var marker = new google.maps.Marker({ position: myLatlng, icon: img, map: map, animation: google.maps.Animation.DROP, title: 'MAP' }); marker.addListener('click', toggleBounce); (function (marker, data) { google.maps.event.addListener(marker, "click", function (e) { var latlng = { lat: parseFloat(marker.position.lat()), lng: parseFloat(marker.position.lng()) }; var geocoder = new google.maps.Geocoder; geocoder.geocode({ 'location': latlng }, function (results, status) { if (status === 'OK') { if (results[1]) { infoWindow.setContent(data.DistName); infoWindow.open(map, marker); } } else { infoWindow.setContent(data.DistName); infoWindow.open(map, marker); } }); }); })(marker, data); } var polyOptions = { path: points, strokeColor: "#FF0000", strokeOpacity: 1, strokeWeight: 3 } var it = new google.maps.Polyline(polyOptions); it.setMap(map); } } if this solved means very easy to build google map
google key from web.config:- <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=<%=ConfigurationManager.AppSettings["GoogleAPIKey"] %>"></script> line map & Route Map:- <script type="text/javascript"> //code by Ethiraj.G on 15.12.2018, ver = 1.01 $(function () { start(); }); function getUrlVars() { var vars = [], hash; var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'); for (var i = 0; i < hashes.length; i++) { hash = hashes[i].split('='); vars.push(hash[0]); vars[hash[0]] = hash[1]; } return vars; } function isEmpty(str) { return typeof str == 'string' && !str.trim() || typeof str == 'undefined' || str === null || str == 0; } $(function () { var h = $(window).height(); h = h - 100; w = $(window).width(); }); /* function start() { var UserID = getUrlVars()['ID']; var paramstr = ''; paramstr += "#EmpID$" + UserID; paramstr += "~#Date$" + '<%= Session["Date"] %>'; paramstr += "~#UserID$" + '<%= Session["UserTypeID"] %>'; paramstr += "~#UserTypeID$" + '<%= Session["UserTypeID"] %>'; paramstr += "~#Type$" + 'V'; var markers = GetRowData_Tables("DBSP_Rpt_MDOSub_ActivityPlan", paramstr, "Sample.aspx/GetRowData_Tables"); if (!isEmpty(markers)) { var mapOptions = { center: new google.maps.LatLng(markers[0].Lat, markers[0].Lon), zoom: 16, mapTypeId: google.maps.MapTypeId.ROADMAP }; var infoWindow = new google.maps.InfoWindow(); var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions); var start = ''; var points = []; for (i = 0; i < markers.length; i++) { img = "icons/" + (i+1) + ".png"; var data = markers[i]; myLatlng = new google.maps.LatLng(data.Lat, data.Lon); points.push(new google.maps.LatLng(data.Lat, data.Lon)); var marker = new google.maps.Marker({ position: myLatlng, icon: img, map: map, title: 'MAP' }); (function (marker, data) { google.maps.event.addListener(marker, "click", function (e) { var latlng = { lat: parseFloat(marker.position.lat()), lng: parseFloat(marker.position.lng()) }; var geocoder = new google.maps.Geocoder; geocoder.geocode({ 'location': latlng }, function (results, status) { if (status === 'OK') { if (results[1]) { var dist = ''; //infoWindow.setContent('<b> Names :</b> ' + data.Names + '<br /><b> Emp Name :</b> ' + data.EmpName + '<br /><b> StartTime :</b> ' + data.StartTime + '<br /><b> End Time :</b> ' + data.EndTime + '<br /><b> StartDate :</b> ' + data.StartDate + '<br /><b> Location :</b> ' + results[1].formatted_address + '<br /><b> Dist Name :</b> ' + data.DistName + '<br />'); infoWindow.setContent( data.DistName ); infoWindow.open(map, marker); } } else { //infoWindow.setContent('<b> Names :</b> ' + data.Names + '<br /><b> Emp Name :</b> ' + data.EmpName + '<br /><b> StartTime :</b> ' + data.StartTime + '<br /><b> End Time :</b> ' + data.EndTime + '<br /><b> StartDate :</b> ' + data.StartDate + '<br /><b> Location :</b> ' + results[1].formatted_address + '<br /><b> Dist Name :</b> ' + data.DistName + '<br />'); infoWindow.setContent( data.DistName ); infoWindow.open(map, marker); } }); }); })(marker, data); } var polyOptions = { path: points, strokeColor: "#FF0000", strokeOpacity: 1, strokeWeight: 3 } var it = new google.maps.Polyline(polyOptions); it.setMap(map); } } */ function start() { var UserID = getUrlVars()['ID']; var paramstr = ''; paramstr += "#EmpID$" + UserID; paramstr += "~#Date$" + '<%= Session["Date"] %>'; paramstr += "~#UserID$" + '<%= Session["UserTypeID"] %>'; paramstr += "~#UserTypeID$" + '<%= Session["UserTypeID"] %>'; paramstr += "~#Type$" + 'V'; //debugger var markers = GetRowData_Tables("DBSP_Rpt_MDOSub_ActivityPlan", paramstr, "Sample.aspx/GetRowData_Tables"); if (!isEmpty(markers)) { var directionsService = new google.maps.DirectionsService; map = new google.maps.Map(document.getElementById("map_canvas"), { center: new google.maps.LatLng(markers[0].HOLat, markers[0].HOLng), zoom: 10, mapTypeId: google.maps.MapTypeId.ROADMAP }); var start1 = [], end1 = []; var img = ''; for (i = 0; i < markers.length; i++) { var data = markers[i]; var img= 'icons/' + (i+1) + ".png"; start1 = new google.maps.LatLng(markers[0].HOLat, markers[0].HOLng); end1 = new google.maps.LatLng(data.Lat, data.Lon); var directionsDisplay = new google.maps.DirectionsRenderer({ map: map, polylineOptions: { strokeColor: '#03a5ef' }, strokeOpacity: 5.0, strokeWeight: 50, suppressMarkers: true }); DisplayRoute(directionsService, directionsDisplay, start1, end1, map, data, img); } } } function DisplayRoute(directionsService, directionsDisplay, start1, end1, map, data, img) { directionsService.route({ origin: start1, destination: end1, travelMode: 'DRIVING', optimizeWaypoints : true }, function (response, status) { if (status === 'OK') { directionsDisplay.setDirections(response); var legs = response.routes[0].legs; for (i=0;i<legs.length;i++) { if(i == 0) { var img1 = "icons/" + "0.png"; var cs = '<div>' +data.Discription+'</div>'; createMarkerfarmer(legs[i].start_location, cs, img1); } var cs = '<div>' + data.DistName + '<br/><b> Distance: '+ response.routes[0].legs[0].distance.text +'</b></div>'; createMarkerfarmer(legs[i].end_location, cs, img); } } }); } function createMarkerfarmer(latlng, contentString, marker_icon) { var marker = new google.maps.Marker({ position: latlng, map: map, animation: google.maps.Animation.DROP, icon: marker_icon, strokeColor: '#FF0000', strokeOpacity: 0.8, strokeWeight: 1, fillOpacity: 0.8, clickable: true }); var infoWindow = new google.maps.InfoWindow({ content: contentString }); google.maps.event.addListener(marker, 'click', function () { infoWindow.open(map, marker); }); } function Map_Date(date) { var newDate = ''; if (date.length > 0) { date = date.split('/'); newDate = date[2] + '/' + date[1] + '/' + date[0]; } return newDate; } function GetRowData_Tables(procName, paramstr, url) { var rowData; $.ajax({ url: url, type: "POST", dataType: "json", async: false, data: "{procedureName: '" + procName + "',paramstr: '" + paramstr + "'}", contentType: "application/json; charset=utf-8", success: function (data) { if (!isEmpty(data.d)) rowData = $.parseJSON(data.d); else rowData = '[]'; }, error: function (error) { } }); return rowData; } //code by Ethiraj.G on 15.12.2018, ver = 1.01 </script> commented lines are line map rest of that Road Map working fine
google maps marker clusterer not working but no errors
This is my first experience with GoogleMaps/JS. My map is working as expected with individual markers. But when i add marker cluster function its not working and the best part is no errors on the console. Below is my code. Any help would be greatly appreciated. function CreateMap(rootElement,data,startPin,endPin){ //console.log("startPin : " + startPin); var google = window.google; var map; var marker; var posInfoWindow; var markers = []; var markersArray = []; var mapElement = rootElement.querySelector('.my-map'); currPos = localStorage.currentPosition; var currentPosition = JSON.parse(localStorage.currentPosition); var results = JSON.parse(data); var defaultIcon, selectedIcon, mainIcon; function centerOnMyLocation() { closeAllInfoWindows(); map.panTo(marker.getPosition()); posInfoWindow.open(map, marker); } function closeAllInfoWindows() { if(posInfoWindow !== void 0) { posInfoWindow.close(); } markers.forEach(function(it) { it.infoWindow.close(); it.marker.setIcon(defaultIcon); }); } function showInfoWindow(idx) { closeAllInfoWindows(); if(map !== void 0) { markers[idx].infoWindow.open(map, markers[idx].marker); markers[idx].marker.setIcon(selectedIcon); } } function highlightListItem(idx) { var items = rootElement.querySelectorAll('.my-result-list-item'); [].forEach.call(items, function(it) { it.className = it.className.replace('my-result-list-item-highlight', ''); }); items[idx].className += ' my-result-list-item-highlight'; } function selectMarker(idx) { showInfoWindow(idx); highlightListItem(idx); } defaultIcon = { url: "/maps/Locator_Green_Pin.png", anchor: new google.maps.Point(0, 0), labelOrigin: new google.maps.Point(34, 35) }; selectedIcon = { url: "/maps/Locator_Yellow_Pin.png", anchor: new google.maps.Point(0, 0), labelOrigin: new google.maps.Point(34, 35) }; mainIcon = { url: "/maps/Locator_Blue_Pin.png", anchor: new google.maps.Point(0, 0) }; var myLatlng = new google.maps.LatLng(currentPosition.latitude, currentPosition.longitude); map = new google.maps.Map(mapElement, { center: myLatlng, zoom: 3, styles: [ { featureType: 'poi', stylers: [{ visibility: 'off' }] // Turn off points of interest. }, { featureType: 'transit.station', stylers: [{ visibility: 'off' }] // Turn off bus stations, train stations, etc. } ], 'mapTypeId': google.maps.MapTypeId.ROADMAP, disableDoubleClickZoom: false, scaleControl: true }); map.addListener('click', function() { closeAllInfoWindows(); }); bounds = new google.maps.LatLngBounds(); // MapAutoZoom : to fit the markers on the map //alert("working on map"); //results.forEach(function(it, idx) { $.each(results, function(idx, it) { //console.log("it : " + it + " , idx : "+idx); var labelXoffset = -30; var labelYOffset = -28; //reduce x offset to center longer labels if (idx >= 9 && idx <= 98) { labelXoffset = -27; } else if ( idx >= 99 && idx <= 998 ) { labelXoffset = -24; } if(startPin<= idx && idx<= endPin){ var m = new MarkerWithLabel({ position: new google.maps.LatLng(it.Latitude, it.Longitude), title: it.MerchantName, animation: google.maps.Animation.DROP, draggable: false, map: map, labelContent: (idx+1).toString(), labelAnchor: new google.maps.Point(labelXoffset, labelYOffset), icon: defaultIcon }); m.addListener('click', function() { if (idx !== -1) { showInfoWindow(idx); highlightListItem(idx); } }); var iw = new google.maps.InfoWindow({ content: "<div class='my-info-window'>View details</div>" }); var obj = { marker: m, infoWindow: iw }; markers.push(obj); var latlongVal = new google.maps.LatLng(data[i].latitude, data[i].longitude); var markerVal = new google.maps.Marker({ position: latlongVal }); markersArray.push(markerVal); bounds.extend(m.position);//MapAutoZoom } if(idx== endPin) return false; }); console.log(markersArray); map.fitBounds(bounds); // MapAutoZoom : auto-zoom map.panToBounds(bounds); // MapAutoZoom : auto-center marker = new google.maps.Marker({ position: myLatlng, title: "Me", animation: google.maps.Animation.DROP, icon: mainIcon }); marker.setMap(map); posInfoWindow = new google.maps.InfoWindow({ content: "My current location" }); marker.addListener('click', function() { showInfoWindow(posInfoWindow, marker, map); }); // // Custom Current Position Control // var centerControlDiv = document.createElement('div'); var div = document.createElement('div'); div.id = 'goToMeUI'; div.className = 'my-map-current-position-control-container'; div.title = 'Click to show your current position'; centerControlDiv.appendChild(div); centerControlDiv.index = 1; var img = document.createElement('img'); img.src = '/maps/Locator_Blue_Pin.svg'; div.appendChild(img); div.addEventListener('click', centerOnMyLocation); map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(centerControlDiv); // // List item click event handling // $( '.my-result-list-item', rootElement ).on('click', function(event) { //alert("map result clicked"); selectMarker(event.currentTarget.getAttribute('data-map-list-index')); }); function initialize(){ var markerCluster = new MarkerClusterer(map, markersArray, {imagePath: '/maps/cluster/m'}); } google.maps.event.addDomListener(window, 'load', initialize); }
Drawing lines from one marker to all other markers and open infowindows of each marker for click
Please click here for screen shot I have Google map which shows the relation between locations based on a condition. What I need is to draw lines from one marker to all other markers and open info windows of each marker for marker click. Can anybody suggest the way to perform the task?
var Markerss = {}; var linearray = []; function initialize() { var markers = [{ 'lat': '32.803', 'lon': '-96.7699', 'ExpertsCount': 2, 'Type': 'ofsite' }, { 'lat': '44.9542', 'lon': '-93.1139', 'ExpertsCount': 3, 'Type': 'onsite' }, { 'lat': '32.903', 'lon': '-150.0011', 'ExpertsCount': 5, 'Type': 'offsite' }, { 'lat': '61.85', 'lon': '-97.6501', 'ExpertsCount': 9, 'Type': 'onnsite' }]; var mapProp = { center: new google.maps.LatLng(28.067768, 2.150065), zoom: 5, mapTypeId: 'terrain' }; //var infowindow = new google.maps.InfoWindow({ // content: "Hello World!" //}); var map = new google.maps.Map(document.getElementById("googleMap"), mapProp); var icon = ""; for (i = 0; i <= markers.length; i++) { var data = markers[i]; var myLatlng = new google.maps.LatLng(parseFloat(data.lat), parseFloat(data.lon)); if (data.Type == "offsite") { icon = 'http://maps.google.com/mapfiles/ms/icons/green-dot.png'; } else if (data.Type == "onsite") { icon = 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png'; } else { icon = 'http://maps.google.com/mapfiles/ms/icons/red-dot.png'; } var div = document.createElement('DIV'); div.innerHTML = '<div class="mapicon" id="dvIcon" style="background-image: url(images/mapiconsmall.png);" onmouseover="javascript:$(this).next().show()" onmouseout="javascript:$(this).next().hide()" ><div class="maindiv"style="width:24px;margin-top:3px; text-align:center;margin-left:1px;"><span style="font-weight:bolder;font-size:11px;"> ' + data.ExpertsCount + '</span></div></div><div id="dvExpName" style="display:none;z-index:1;position:absolute;">' + data.expName + '</div>'; var marker = new google.maps.Marker({ position: myLatlng, map: map, title: i, content: div, flat: true, anchor: RichMarkerPosition.MIDDLE, icon: icon }); Markerss[i] = marker; //if (data.Type == "onsite") { // Marker[i].setClickable = false; //} //else { // Marker[i].setClickable = true; //} // Attaching a click event to the current marker if (markers[i].Type != "onsite") { google.maps.event.addListener(marker, 'click', function (event) { if (linearray.length != 0) { for (i = 0; i < linearray.length; i++) { linearray[i].setMap(null); } } var lineSymbol = { path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW, scale: 3, strokeColor: 'red' }; for (j = 0; j < markers.length; j++) { var marker = markers[j]; var lat = parseFloat(markers[j].lat); var lon = parseFloat(markers[j].lon); if (lat != event.latLng.lat()) { var line = new google.maps.Polyline({ path: [{ lat: event.latLng.lat(), lng: event.latLng.lng() }, { lat: lat, lng: lon }], icons: [{ icon: lineSymbol, offset: '100%' }], strokeColor: 'red', map: map }); linearray.push(line); } var infoWindow = new google.maps.InfoWindow({ content: '<b><i>Expert Count:</i></b> <span>' + parseInt(markers[j].ExpertsCount) + '</span><br/><b><i>Expert Count:</i></b> <span>' + parseInt(markers[j].ExpertsCount) + '</span><br/>' }); infoWindow.open(map, Markerss[j]); } }); } } }
Google Maps show marker inside a cluster
Is it possible to zoom to a marker if it's inside a marker cluster? I am changing the color of the markers if a user hovers over a html div. But if the marker is inside a cluster, the color won't change since the marker itself is not shown. Could anyone provide me with possible ways of solving this issue? var allMarkers = []; (function($) { "use strict"; // Custom options for map var options = { zoom: 12, mapTypeId: 'Styled', disableDefaultUI: true, panControl: true, zoomControl: true, scaleControl: true, mapTypeControlOptions: { mapTypeIds: ['Styled'] } }; var styles = [{ stylers: [{ hue: "#cccccc" }, { saturation: -100 }] }, { featureType: "road", elementType: "geometry", stylers: [{ lightness: 100 }, { visibility: "simplified" }] }, { featureType: "road", elementType: "labels", stylers: [{ visibility: "on" }] }, { featureType: "poi", stylers: [{ visibility: "off" }] }]; var newMarker = null; var markers = []; // json for properties markers on map var props = < ? php echo json_encode($map_flats); ? > ; // custom infowindow object var infobox = new InfoBox({ disableAutoPan: false, maxWidth: 202, pixelOffset: new google.maps.Size(-101, -285), zIndex: null, boxStyle: { background: "url('images/infobox-bg.png') no-repeat", opacity: 1, width: "202px", height: "245px" }, closeBoxMargin: "28px 26px 0px 0px", closeBoxURL: "", infoBoxClearance: new google.maps.Size(1, 1), pane: "floatPane", enableEventPropagation: false }); // function that adds the markers on ma var addMarkers = function(props, map) { $.each(props, function(i, prop) { var latlng = new google.maps.LatLng(prop.position.lat, prop.position.lng); var marker = new google.maps.Marker({ position: latlng, map: map, id: +prop.id, icon: new google.maps.MarkerImage( 'images/' + prop.markerIcon, null, null, null ), draggable: false, animation: google.maps.Animation.DROP, }); var bounds = new google.maps.LatLngBounds(); for (i = 0; i < markers.length; i++) { bounds.extend(markers[i].getPosition()); } map.fitBounds(bounds); allMarkers.push(marker); //Add it to allMarkers var infoboxContent = '<div class="infoW">' + '<div class="propImg">' + '<img src="uploads/' + prop.image + '">' + '<div class="propBg">' + '</div>' + '</div>' + '<div class="paWrapper">' + '<div class="propTitle">€' + prop.title + '</div>' + '<div class="propAddress">' + prop.address + '</div>' + '</div><br>' + '<ul class="propFeat">' + '<li><span class="fa fa-moon-o"></span> ' + prop.bedrooms + ' room(s)</li>' + '<li><span class="icon-frame"></span> ' + prop.area + ' m<sup>2</sup></li>' + '</ul>' + '<div class="clearfix"></div>' + '<div class="infoButtons">' + '<a class="btn btn-sm btn-round btn-gray btn-o closeInfo">Close</a>' + '<a target="_blank" href="single.php?id=' + prop.id + '" class="btn btn-sm btn-round btn-green viewInfo">View</a>' + '</div>' + '</div>'; google.maps.event.addListener(marker, 'click', (function(marker, i) { return function() { infobox.setContent(infoboxContent); infobox.open(map, marker); } })(marker, i)); google.maps.event.addListener(map, "click", function(event) { infobox.close(); }); $(document).on('click', '.closeInfo', function() { infobox.open(null, null); }); markers.push(marker); }); //set style options for marker clusters (these are the default styles) var mcOptions = { styles: [{ height: 53, url: "images/m1.png", width: 53 }, { height: 54, url: "images/m1.png", width: 54 }, { height: 66, url: "http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/images/m3.png", width: 66 }, { height: 78, url: "http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/images/m4.png", width: 78 }, { height: 90, url: "http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/images/m5.png", width: 90 }], gridSize: 50, maxZoom: 14 } //init clusterer with your options var mc = new MarkerClusterer(map, markers, mcOptions);
The Cluster doesn't change color (yet ?). But I do have code that detects if the client hovers over his marker inside the cluster. So, now it logs a message onyour screen. Look at the scripts I load. Google Maps, MarkerClustererPlus and a script containing data. Many locations (of photographs). So, the marker of the client, is the marker in Central Park, New York, USA. Try it out. Any other idea how to visualize the detection? Like add a circle around the cluster, ... ? <script src="http://maps.google.com/maps/api/js"></script> <script src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclustererplus/src/markerclusterer.js"></script> <script src="https://googlemaps.github.io/js-marker-clusterer/examples/data.json"></script> <script> var client_index = 821; // Central Park, New York. Item 821 ( "photo_id": 586159 ) // We run through all the marker-objects inside the cluster; and we see if the marker object of our client marker is inside that array function clientMarkerInCluster(allMarkers, markersInCluster) { if(markersInCluster.indexOf( allMarkers[client_index] ) > 0) { return true; } return false; } function initialize() { var center = new google.maps.LatLng(40.480467417349345,-98.80444335937501); var options = { 'zoom': 4, 'center': center, 'mapTypeId': google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("map"), options); var markers = []; for(var key in data.photos) { markers.push(new google.maps.Marker({ position: new google.maps.LatLng(data.photos[key].latitude, data.photos[key].longitude), map: map, title: key +' '+ data.photos[key].photo_title }) ); } var mcOptions = {gridSize: 50, maxZoom: 15}; var mc = new MarkerClusterer(map, markers, mcOptions); google.maps.event.addListener(mc, "mouseover", function (c) { if(clientMarkerInCluster(markers, c.markers_)) { log('Client marker is inside the cluster'); } }); // google.maps.event.addListener(mc, "mouseout", function (c) {}); } google.maps.event.addDomListener(window, 'load', initialize); // just a function to show a log on screen function log(h) { document.getElementById("log").innerHTML += h + "<br>"; } </script> <style> #map { height: 400px; } </style> <div id="map"></div> <div id="log"></div>
Ionic Framework-Can't move or drag the map in wp8
I have a main menu and an item to access the map view. for the first time the map is run according to expectation. the map also can zoom in-out, centerOnMe, and I can give a marker to the position. But when I move or drag the map, the map view was close suddenly and back to main menu. and when I try to access the map again, the map view show but with the main menu view half of it. Here is my js code : angular.module('starter.controllers') .controller('LokasiBayarCtrl', function($scope, $ionicLoading, $location, $compile) { $scope.go = function(path) { $location.path(path); }; var map, infoWindow, mapservice, myLatlng = new google.maps.LatLng(-33.8668283734, 151.2064891821), mapOptions = { //center: myLatlng, zoom: 15, mapTypeId: google.maps.MapTypeId.ROADMAP, mapTypeControl: false }, iconsBase = 'img/marker/', icons = { atm: { icon: iconsBase + 'pln.png' } }; // Marker + infowindow + angularjs compiled ng-click var contentString = "<div><a ng-click='clickTest()'>Click me!</a></div>"; var compiled = $compile(contentString)($scope); var mapHeight = Math.round( 3 / 5 * window.SCREEN_HEIGHT ); mapHeight = ( window.SCREEN_HEIGHT < 500 ) ? 240 : mapHeight; $scope.mapHeight = mapHeight; console.log("map height: " + mapHeight + " screenH: " + window.SCREEN_HEIGHT); function loading(){ $ionicLoading.show({ content: 'Getting current location...', showBackdrop: false //true }); } function loadingDone(){ $ionicLoading.hide(); } function centerOnMe(){ if(!$scope.map) { return; } loading(); function successCb(pos) { myLatlng = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude); $scope.map.setCenter(myLatlng); var myPosMarker = new google.maps.Marker({ position: map.getCenter(), icon: { path: google.maps.SymbolPath.CIRCLE, scale: 10 }, draggable: false, map: map }); console.log(pos.coords); console.log('centerOn Me :', map); searchPlaces(); loadingDone(); } function errorCb_highAccuracy(error){ console.log('errorCb_highAccuracy : Unable to get location: ' + error.message); if (error.code == error.TIMEOUT) { // Attempt to get GPS loc timed out after 5 seconds, // try low accuracy location console.log("attempting to get low accuracy location"); navigator.geolocation.getCurrentPosition( successCb, errorCb_lowAccuracy, {maximumAge:600000, timeout:10000, enableHighAccuracy: false}); return; } var msg = "Can't get your location (high accuracy attempt). Error = "; if (error.code == 1) msg += "PERMISSION_DENIED"; else if (error.code == 2) msg += "POSITION_UNAVAILABLE"; msg += ", msg = "+error.message; loadingDone(); console.log(msg); } function errorCb_lowAccuracy(error){ var msg = "Can't get your location (low accuracy attempt). Error = "; if (error.code == 1) msg += "PERMISSION_DENIED"; else if (error.code == 2) msg += "POSITION_UNAVAILABLE"; else if (error.code == 3) msg += "TIMEOUT"; msg += ", msg = "+error.message; loadingDone(); console.log(msg); alert(msg); } navigator.geolocation.getCurrentPosition( successCb, errorCb_highAccuracy, { maximumAge:600000, timeout:5000, enableHighAccuracy: true }); } function initialize() { console.log('init'); map = new google.maps.Map(document.getElementById("map"), mapOptions); infoWindow = new google.maps.InfoWindow({ content: compiled[0] }); mapservice = new google.maps.places.PlacesService(map); $scope.map = map; google.maps.event.addListener(map, 'bounds_changed', searchPlaces); google.maps.event.addListener(map, 'zoom_changed', searchPlaces); google.maps.event.addListener(map, 'center_changed', searchPlaces); google.maps.event.addListener(map, 'resize', searchPlaces); google.maps.event.addListener(map, 'idle', function () { document.getElementById("map").setAttribute("style", "min-height: 240px; height: "+$scope.mapHeight+"px; position: relative; background-color: rgb(229, 227, 223); overflow: hidden; -webkit-transform: translateZ(0px);"); console.log(document.getElementById("map").getAttribute("style")); var center = map.getCenter(); google.maps.event.trigger(map, 'resize'); map.setCenter(center); }); centerOnMe(); } function getPlaceData(result){ return { name: result.name, address_fmt: result.formatted_address, icon: result.icon, types: result.types, vicinity: result.vicinity, phone: result.formatted_phone_number, website: result.website }; } function searchPlaces(){ console.log('searchPlaces'); // nearby search var request = { location: myLatlng, radius: '1000', types: ['atm', 'bank'], rankby: 'prominence' }; mapservice.nearbySearch(request, searchCb); } function searchCb(results, status){ if (status != google.maps.places.PlacesServiceStatus.OK) { console.log('error'); //alert(status); console.log(status); return; } console.log(results.length); for (var i = 0; i < results.length; i++) { createMarker(results[i]); } /*for (var i = 0, result; result = results[i]; i++) { //if (i < 3) { console.log(result); } console.log('success'); createMarker(result); }*/ } function createMarker(place) { var marker = new google.maps.Marker({ map: map, position: place.geometry.location, icon : icons['atm'].icon }); google.maps.event.addListener(marker, 'click', function() { mapservice.getDetails(place, function(result, status) { if (status != google.maps.places.PlacesServiceStatus.OK) { alert(status); return; } console.log(result); infoWindow.setContent(result.name); infoWindow.open(map, marker); $scope.place = getPlaceData(result); console.log($scope.place); $scope.$apply(); // ZUL : quick and dirty }); }); } //google.maps.event.addDomListener(window, 'load', initialize); $scope.centerOnMe = function() { centerOnMe(); }; $scope.clickTest = function() { alert('Example of infowindow with ng-click') }; // main initialize(); $scope.place = null; }); Please can any one can tell me what's wrong with my code? Previously I apologize because my english is bad, I would be grateful much if anyone can help me.