I am trying to fix a bug in existing code.
I'm new to javascript and css.
The program was developed in .net vistual studio.
The problem is this: I have a page that has a map where I make a circle in a region of it. The behavior the system should have is when I click the circle button, the system should open a form with information from the region where I made the circle. However, when I expand the map, the form is hidden behind the map. Can anyone tell me how I can bring this form forward in the expanded map form? In the attached image, the window behind the map appears in blue.
click to see map image
function configPontosMapa(sender, args) {
var label, marker, dataItem, location, circle, coordenadas, polygon, tableView, lats,
lngs, idPonto, nome, barra, shape, idPtoGlobalAux;
var dataItems = $find(gridPontos).get_masterTableView().get_dataItems();
var latlngBounds = new google.maps.LatLngBounds();
mapa.ClearMap();
MapaLabel.ClearLabels();
clearMapaBotao();
clearMapaBotaoSubPonto();
for (var i = 0; i < dataItems.length; i++) {
dataItem = dataItems[i];
idPonto = dataItem.getDataKeyValue("IdPontoGeografico");
idPtoGlobalAux = dataItem.getDataKeyValue("IdPontoGlobal");
nome = dataItem.getDataKeyValue("Nome");
lats = dataItem.getDataKeyValue("LatitudesFormatadas").split('|');
lngs = dataItem.getDataKeyValue("LongitudesFormatadas").split('|');
if (lats.length == 1) {
location = new google.maps.LatLng(parseFloat(lats[0]), parseFloat(lngs[0]));
var raio = parseFloat(dataItem.getDataKeyValue("Raio"));
if (!raio) {
raio = 1;
}
circle = new google.maps.Circle({
center: location,
radius: raio,
strokeColor: corPadrao,
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: corPadrao,
fillOpacity: 0.15,
map: mapa.Mapa,
entity: idPonto,
idPontoGlobal: idPtoGlobalAux,
zIndex: 0
});
if (idPtoGlobalAux) {
barra = new MapaBarraBotao(mapa.Mapa, circle.getCenter(), circle, showModalPontoGlobal);
}
else {
barra = new MapaBarraBotao(mapa.Mapa, circle.getCenter(), circle, showModalNovoPonto);
}
circle.barraBotao = barra;
shape = circle;
mapa.NewCircleByShape(circle);
latlngBounds.union(circle.getBounds());
marker = mapa.NewMarker();
marker.bindTo('position', circle, 'center');
marker.setOptions({ ponto: circle, title: nome });
marker.setIcon('../../../Images/Ponto/MarcadorPonto1.png');
//label.bindEvents(marker);
circle.setEditable(true);
circle.barraBotao.ocultaBotaoSalvarCancelar();
google.maps.event.addListener(circle, 'rightclick', function () {
novoSubponto(this);
});
google.maps.event.addListener(circle, 'center_changed', function () {
this.setOptions({ fillColor: corAlterado, strokeColor: corAlterado });
this.barraBotao.draw(this.getCenter());
});
google.maps.event.addListener(circle, 'radius_changed', function () {
this.setOptions({ fillColor: corAlterado, strokeColor: corAlterado });
});
} else {
coordenadas = [];
for (var j = 0; j < lats.length; j++) {
coordenadas[j] = Mapa.NewLatLng(parseFloat(lats[j]), parseFloat(lngs[j]));
}
latlngBounds.extend(coordenadas[0]);
polygon = mapa.NewPolygonByPaths(coordenadas);
polygon.setEditable(true);
polygon.getPath().obj = polygon;
if (idPtoGlobalAux) {
barra = new MapaBarraBotao(mapa.Mapa, polygon.getPath().getAt(0), polygon, showModalPontoGlobal);
}
else {
barra = new MapaBarraBotao(mapa.Mapa, polygon.getPath().getAt(0), polygon, showModalNovoPonto);
}
polygon.barraBotao = barra;
shape = polygon;
polygon.setOptions({
entity: idPonto,
idPontoGlobal: idPtoGlobalAux,
barraBotao: barra,
zIndex: 0
});
marker = mapa.NewMarkerAtPoint(coordenadas[0]);
marker.setOptions({ ponto: polygon, title: nome });
marker.setIcon('../../../Images/Ponto/MarcadorPonto1.png');
polygon.barraBotao.ocultaBotaoSalvarCancelar();
polygon.marker = marker;
google.maps.event.addListener(polygon.getPath(), 'set_at', function () {
var coord = this.getAt(0);
this.obj.setOptions({ fillColor: corAlterado, strokeColor: corAlterado });
this.obj.barraBotao.draw(coord);
this.obj.label.draw(coord);
this.obj.marker.setPosition(coord);
});
google.maps.event.addListener(polygon.getPath(), 'insert_at', function () {
this.obj.setOptions({ fillColor: corAlterado, strokeColor: corAlterado });
this.obj.barraBotao.draw(this.getAt(0));
});
google.maps.event.addListener(polygon, 'rightclick', function () {
novoSubPoligono(this);
});
}
google.maps.event.addListener(marker, 'click', function () {
mapa.Mapa.setCenter(this.getPosition());
mapa.Mapa.setZoom(15);
});
if (idPonto == 0) {
label = createLabel(dataItem.getDataKeyValue("Nome"), null, shape, showModalPontoGlobal);
}
else {
label = createLabel(dataItem.getDataKeyValue("Nome"), null, shape);
}
label.bindEvents(marker);
shape.label = label;
arrayBotao.push(barra);
}
mapa.SetBoundsCircle(latlngBounds);
}
If this form has position prop then you can add z-index to this element.
z-index: 10 should do.
Related
I have create a layergroup of markers. Now i want to listen/fire the onclick event through map.on("click"). i have tried the below code but it is not working.
I am able to do the similar with the polygon layers but getting no output with layer of markers.
please suggest me any way so that i can listen the click event on markers on map.
L1 = new L.LayerGroup();
for (let i = 0; i < data.length; i++) {
var marker = L.circleMarker([data[i].Lat, data[i].Long], 100)
.addTo(map)
.on("mouseover", function () {
this.setStyle({
fillColor: "green",
fillOpacity: 0.8,
});
})
.on("mouseout", function () {
this.setStyle({
fillColor: "blue",
fillOpacity: 0.2,
});
});
L1.addLayer(marker);
marker.on("click", function (e) {
ull = document.getElementById("this3");
ull.innerHTML = "";
var xx = document.getElementById("clickinfo");
xx.style.left = "0px";
var head = document.getElementById("heading3");
head.innerHTML = "Semi Info";
for (const key in data[i]) {
var element = document.createElement("li");
element.style.background = "#cce5ff";
element.style.margin = "5px 5px 5px 5px";
element.innerHTML = `${key}: ${data[i][key]}`;
ull.appendChild(element);
}
});
}
L1.addTo(map);
map.on("click", function (event) {
var latlng = event.latlng;
// L1.fireEvent("click", {
// latlng: latlng,
// layerPoint: event.layerPoint,
// containerPoint: event.containerPoint,
// originalEvent: event.originalEvent,
// layer: L1
// });
var layers = leafletPip.pointInLayer(latlng, L1);
layers.forEach(function (layer) {
L1.fireEvent("click", {
latlng: latlng,
layerPoint: event.layerPoint,
containerPoint: event.containerPoint,
originalEvent: event.originalEvent,
layer: layer,
});
});
// var layers= leafletPip.pointInMarker(latlng,L1);
// layers.forEach(function(layer){
// L1.fireEvent("click",{
// latlng: latlng,
// layerPoint: event.layerPoint,
// containerPoint: event.containerPoint,
// originalEvent: event.originalEvent,
// layer: layer
// });
// });
});
I have a leaflet map with polyline data in. The polyline is styled how I want but what I would like is to have a marker at the centre of each line. Is this possible and if so what changes to the below do I need to make?
var pathstyling = {
stroke: true,
fillColor: "#b5b5b5",
color: "#b5b5b5",
weight: 5,
opacity: 1,
fillOpacity: 0.6,
dashArray: 10,
};
const path = L.geoJSON(path_line, {
style: pathstyling,
})
.bindPopup(function (layer) {
let cap_name = layer.feature.properties.name.replace(
/(^\w{1})|(\s+\w{1})/g,
(letter) => letter.toUpperCase()
);
return `<p>${cap_name}</p><a href="https://${layer.feature.properties.link}" target="_blank">View<a>`;
/******/
})
.addTo(map);
You can simply do this with leaflet core:
function calcMiddleLatLng(map, latlng1, latlng2) {
// calculate the middle coordinates between two markers
const p1 = map.project(latlng1);
const p2 = map.project(latlng2);
return map.unproject(p1._add(p2)._divideBy(2));
}
function createMiddleMarkers(line){
var latlngs = line.getLatLngs();
for(var i = 1; i < latlngs.length; i++){
var left = latlngs[i-1];
var right = latlngs[i];
var newLatLng = calcMiddleLatLng(map,left,right);
L.marker(newLatLng).addTo(map);
}
}
createMiddleMarkers(layer);
https://jsfiddle.net/falkedesign/g7e8w9tz/
I'm using google maps API to allow user draw custom polygons on the map. I need to check and display length of every single border.
I already use Geometry Library and Map Label Library to get and show computed area of polygon (also changing on 'insert_at' and 'set_at' events), but unfortunately I do not know how to get border lengths. Any help will be appreciated.
Used code sample:
var labels = [];
var allOverlays = [];
function setSelection(shape) {
selectedShape = shape;
shape.setEditable(true);
}
function initMap() {
var options = {
zoom: 14,
center: {lat: 52.250618, lng: 20.9774}
}
var map = new google.maps.Map(document.getElementById('map'), options);
var drawingManager = new google.maps.drawing.DrawingManager({
markerOption: {
draggable: false
},
polygonOptions: {
draggable: false,
fillColor: '#5C6BC0',
fillOpacity: 0.45,
strokeWeight: 0,
editable: true,
zIndex: 1
},
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: ['circle', 'polygon']
},
circleOptions: {
fillColor: '#5C6BC0',
fillOpacity: 0.45,
strokeWeight: 0,
editable: true,
zIndex: 1
},
map: map
});
function attachPolygonInfoWindow(polygon) {
var path = polygon.getPath();
var points = path.getArray();
var area = (google.maps.geometry.spherical.computeArea(path.getArray())).toFixed(0);
var bounds = new google.maps.LatLngBounds();
var i;
for (i = 0; i < points.length; i++) {
bounds.extend(points[i]);
}
var boundsCenter = bounds.getCenter();
var mapLabel = new MapLabel({
map: map,
fontSize: 20,
align: 'left'
});
if (!labels.length) {
labels.push(mapLabel)
}
showPolygonInfoWindow(labels, boundsCenter, area);
}
function showPolygonInfoWindow(arr, position, text) {
arr.forEach((el) => {
el.set('position', position);
el.set('text', text + 'm2')
})
}
function removePolygonInfoWindow() {
for (var i = 0; i < labels.length; i++) {
labels[i].setMap(null);
}
labels = [];
}
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(e) {
allOverlays.push(e);
if (e.type != google.maps.drawing.OverlayType.MARKER) {
drawingManager.setDrawingMode(null);
var newShape = e.overlay;
newShape.type = e.type;
google.maps.event.addListener(newShape, 'click', function() {
setSelection(newShape);
});
if (newShape.type == "polygon") {
var path = newShape.getPath();
google.maps.event.addListener(path, 'insert_at', function() {
attachPolygonInfoWindow(newShape);
});
google.maps.event.addListener(path, 'set_at', function() {
attachPolygonInfoWindow(newShape);
});
attachPolygonInfoWindow(newShape);
}
setSelection(newShape);
}
});
}
initMap();
<script src="https://maps.google.com/maps/api/js?sensor=false&libraries=drawing,geometry">
</script>
<script type="text/javascript" src="https://cdn.rawgit.com/googlemaps/js-map-label/gh-pages/src/maplabel.js"></script>
Working example Codepen
I would like to display the length of each border on the side of each border.
My suggestion would be to when you create the center label, also process thru the paths of the polygon, compute their lengths and centers; then create MapLabel objects for each and place it at the center of the side. Something like:
for (var i=0; i<polygon.getPath().getLength(); i++) {
// for each side in path, compute center and length
var start = polygon.getPath().getAt(i);
var end = polygon.getPath().getAt(i<polygon.getPath().getLength()-1 ? i+1 : 0);
var sideLength = google.maps.geometry.spherical.computeDistanceBetween(start,end);
var sideCenter = google.maps.geometry.spherical.interpolate(start, end, 0.5);
var sideLabel = new MapLabel({
map: map,
fontSize: 20,
align: "center"
});
sideLabel.set("position", sideCenter);
sideLabel.set("text", sideLength.toFixed(2)+"m");
polygon.labels.push(sideLabel);
}
proof of concept fiddle
code snippet:
var labels = [];
var allOverlays = [];
function setSelection(shape) {
selectedShape = shape;
shape.setEditable(true);
}
function initMap() {
var options = {
zoom: 14,
center: {
lat: 52.250618,
lng: 20.9774
}
};
var map = new google.maps.Map(document.getElementById("map"), options);
var drawingManager = new google.maps.drawing.DrawingManager({
polygonOptions: {
draggable: false,
fillColor: "#5C6BC0",
fillOpacity: 0.45,
strokeWeight: 0,
editable: true,
zIndex: 1
},
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: ["polygon"]
},
map: map,
drawingMode: 'polygon'
});
function attachPolygonInfoWindow(polygon) {
if (!polygon.labels) polygon.labels = [];
for (var i = 0; i < polygon.labels.length; i++) {
polygon.labels[i].setMap(null);
}
polygon.labels = [];
var path = polygon.getPath();
var points = path.getArray();
var area = google.maps.geometry.spherical
.computeArea(path.getArray())
.toFixed(0);
var bounds = new google.maps.LatLngBounds();
var i;
for (i = 0; i < points.length; i++) {
bounds.extend(points[i]);
}
var boundsCenter = bounds.getCenter();
var centerLabel = new MapLabel({
map: map,
fontSize: 20,
align: "left"
});
polygon.labels.push(centerLabel);
centerLabel.set("position", bounds.getCenter());
centerLabel.set("text", area + "m2");
if (path.getLength() < 2) return;
for (var i = 0; i < polygon.getPath().getLength(); i++) {
// for each side in path, compute center and length
var start = polygon.getPath().getAt(i);
var end = polygon.getPath().getAt(i < polygon.getPath().getLength() - 1 ? i + 1 : 0);
var sideLength = google.maps.geometry.spherical.computeDistanceBetween(start, end);
var sideCenter = google.maps.geometry.spherical.interpolate(start, end, 0.5);
var sideLabel = new MapLabel({
map: map,
fontSize: 20,
align: "center"
});
sideLabel.set("position", sideCenter);
sideLabel.set("text", sideLength.toFixed(2) + "m");
polygon.labels.push(sideLabel);
}
}
function removePolygonInfoWindow() {
for (var i = 0; i < labels.length; i++) {
labels[i].setMap(null);
}
labels = [];
}
google.maps.event.addListener(drawingManager, "overlaycomplete", function(e) {
allOverlays.push(e);
if (e.type != google.maps.drawing.OverlayType.MARKER) {
drawingManager.setDrawingMode(null);
var newShape = e.overlay;
newShape.type = e.type;
google.maps.event.addListener(newShape, "click", function() {
setSelection(newShape);
});
if (newShape.type == "polygon") {
var path = newShape.getPath();
google.maps.event.addListener(path, "insert_at", function() {
attachPolygonInfoWindow(newShape);
});
google.maps.event.addListener(path, "set_at", function() {
attachPolygonInfoWindow(newShape);
});
attachPolygonInfoWindow(newShape);
}
setSelection(newShape);
}
});
}
initMap();
html,
body,
#map {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=drawing"></script>
<script src="https://cdn.jsdelivr.net/npm/js-map-label#1.0.1/src/maplabel.js"></script>
I am working on google map directions I am following the google's navigation app.
I am able to get all the possible alternative routes by DirectionsService and can give the polylines different colors I want the user to be able to select his desired path just bu clicking on the poly lines some how have have not found any thing for this.
My code:
directionsService.route(request, function(response, status) {
var points = [];
if (status == google.maps.DirectionsStatus.OK) {
try {
var polycolour = "";
var Opacity = 0;
//var PolyLine = '';
for (var i = 0, len = response.routes.length; i < len; i++) {
if (i == 0) {
polycolour = "Blue";
Opacity = 5;
}
else {
polycolour = "grey";
Opacity = 2;
}
directionsDisplay = new google.maps.DirectionsRenderer({
map: map,
directions: response,
routeIndex: i,
draggable : true,
polylineOptions: {
strokeColor: polycolour,
strokeWeight: Opacity
}
});
var infowindow2 = new google.maps.InfoWindow();
//var step = 10;
//alert(angular.toJson(response.routes[0].legs[0].steps[i]));
infowindow2.setContent(""+((response.routes[i].legs[0].distance.value)/1000)+" KM");
infowindow2.setPosition(response.routes[i].legs[0].steps[8].end_location);
infowindow2.open(map);
}
//directionsDisplay.setMap(map);
google.maps.event.addListener(directionsDisplay, 'click', function(){
alert("helo");
});
//for (var k = 0, len = response.routes.length; k < len; k++) {
//var myRoute = response.routes[k].legs[0];
//for (var i = 0; i < myRoute.steps.length; i++) {
//for (var j = 0; j < myRoute.steps[i].lat_lngs.length; j++) {
// points.push(myRoute.steps[i].lat_lngs[j]);
//}
//}
//var routLine = new google.maps.Polyline(
//{
//path: points,
//strokeColor: "Red",
//strokeOpacity: 0.5,
// strokeWeight: 10
// }
// );
// }
// routLine.setMap(map)
// Add a listener for the rightclick event on the routLine
//google.maps.event.addListener(routLine, 'click', function(e){
//try {
//alert(angular.toJson(e));
//}
//catch (err)
//{
// alert(err);
//}
// });
//alert(angular.toJson(response.routes[0].legs[0].steps));
//google.maps.event.addListener(PolyLine, 'routeindex_changed', function() {
//alert("Bingo");
//computeTotalDistance(directionsDisplay.getRouteIndex());
//});
//alert(response.routes.length);
//directionsDisplay.setDirections(response);
}
catch (err)
{
alert(err);
}
}
});
First you need to tell the request that you want alternative routes, like this
// for example
var request = {
origin: start,
destination: end,
provideRouteAlternatives: true,
travelMode: google.maps.TravelMode[DRIVING]
};
Then you have multiple response.routes objects (notice, sometimes you only get 1 route).
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
for(var i in response.routes ) {
// ...
}
}
}
Now you can use response.routes[i] as the source for direction render.
Or you make your own polyline. Use response.routes[i].overview_path as the path
var line = new google.maps.Polyline({
path: response.routes[i].overview_path,
strokeColor: "#ff0000", // you might want different colors per suggestion
strokeOpacity: 0.7,
strokeWeight: 3
});
line.setMap(map);
Here is an functioning example.
Just change your API key.
As you asked for, clicking on a route highlights it
UPDATE: I like it this way.
Both grey lines and colored lines are generated. But highlighting only shows 1 of the suggestions on the map.
The big, grey line is nice to click on. So it gets the click event instead of the colored line.
This is also the easiest way to avoid the Z-index problem.
And I store data (duration, distance), that I show on an infoWindow
<!DOCTYPE html>
<html>
<head>
<title>Google Map Direction Render Alternate Route How To Select Desired Path</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 90%;
}
</style>
</head>
<body>
<form id="form">
<input id="from" placeholder="From" value="Brussel" />
<input id="to" placeholder="To" value="Antwerpen" />
<input type="submit" value="GO" />
</form>
<div id="map"></div>
<div id="info">
Stackoverflow
</div>
<script type="text/javascript" src="https://maps.google.com/maps/api/js?key=YOUR_API_KEY&libraries=geometry"></script>
<script>
var map;
var directionsService;
var polylines = [];
var shadows = [];
var data = [];
var infowindow;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 50.84659376378408, lng: 4.3531406857355215},
zoom: 12,
mapTypeId: 'terrain'
});
google.maps.event.addDomListener(document.getElementById('form'), 'submit', function(e) {
calcRoute(
document.getElementById('from').value,
document.getElementById('to').value
);
// prevent the form from really submitting
e.preventDefault();
return false;
});
directionsService = new google.maps.DirectionsService();
// get the bounds of the polyline
// http://stackoverflow.com/questions/3284808/getting-the-bounds-of-a-polyine-in-google-maps-api-v3
google.maps.Polyline.prototype.getBounds = function(startBounds) {
if(startBounds) {
var bounds = startBounds;
}
else {
var bounds = new google.maps.LatLngBounds();
}
this.getPath().forEach(function(item, index) {
bounds.extend(new google.maps.LatLng(item.lat(), item.lng()));
});
return bounds;
};
}
// this function calculates multiple suggested routes.
// We will draw 3 (broad stroke) suggested routs in grey. These are broad to click on them easier.
// We duplicate these routes with a thin, colored line; only route 0 is shown.
function calcRoute(start, end) {
var request = {
origin: start,
destination: end,
provideRouteAlternatives: true,
unitSystem: google.maps.UnitSystem.METRIC,
travelMode: google.maps.TravelMode['DRIVING']
};
directionsService.route(request, function(response, status) {
// clear former polylines
for(var j in polylines ) {
polylines[j].setMap(null);
shadows[j].setMap(null);
}
polylines = [];
shadows = [];
data = [];
if (status == google.maps.DirectionsStatus.OK) {
var bounds = new google.maps.LatLngBounds();
for(var i in response.routes) {
// let's make the first suggestion highlighted;
var hide = (i==0 ? false : true);
var shadow = drawPolylineShadow(response.routes[i].overview_path, '#666666');
var line = drawPolyline(response.routes[i].overview_path, '#0000ff', hide);
polylines.push(line);
shadows.push(shadow);
// let's add some data for the infoWindow
data.push({
distance: response.routes[i].legs[0].distance,
duration: response.routes[i].legs[0].duration,
end_address: response.routes[i].legs[0].end_address,
start_address: response.routes[i].legs[0].start_address,
end_location: response.routes[i].legs[0].end_location,
start_location: response.routes[i].legs[0].start_location
});
bounds = line.getBounds(bounds);
google.maps.event.addListener(shadow, 'click', function(e) {
// detect which route was clicked on
var index = shadows.indexOf(this);
highlightRoute(index, e);
});
}
map.fitBounds(bounds);
}
});
}
// this makes one of the colored routes visible.
function highlightRoute(index, e) {
for(var j in polylines ) {
if(j==index) {
//var color = '#0000ff';
polylines[j].setMap(map);
// feel free to customise this string
var contentString =
'<span>'+ data[j].distance.text +'</span><br/>'+
'<span>'+ data[j].duration.text +'</span><br/>'+
'<span>route: '+ j +'</span><br/>'+
//'From: <span>'+ data[j].start_address +'</span><br/>'+
//'To: <span>'+ data[j].end_address +'</span><br/>'+
'';
if(e) {
var position = new google.maps.LatLng(e.latLng.lat(), e.latLng.lng());
// it may be needed to close the previous infoWindow
if(infowindow) {
infowindow.close();
infowindow = null;
}
infowindow = new google.maps.InfoWindow({
content: contentString,
position: position,
map: map
});
//infowindow.open(map, polylines[j]);
}
}
else {
polylines[j].setMap(null);
}
}
}
// returns a polyline.
// if hide is set to true, the line is not put on the map
function drawPolyline(path, color, hide) {
var line = new google.maps.Polyline({
path: path,
strokeColor: color,
strokeOpacity: 0.9,
strokeWeight: 3
});
if(! hide) {
line.setMap(map);
}
return line;
}
function drawPolylineShadow(path, color, hide) {
var line = new google.maps.Polyline({
path: path,
strokeColor: color,
strokeOpacity: 0.4,
strokeWeight: 7
});
if(! hide) {
line.setMap(map);
}
return line;
}
google.maps.event.addDomListener(window, 'load', initMap);
</script>
</body>
</html>
earlier code. this changes the color of the polyLine
<!DOCTYPE html>
<html>
<head>
<title>Suggested routes</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 90%;
}
</style>
</head>
<body>
<form id="form">
<input id="from" placeholder="From" value="Brussel" />
<input id="to" placeholder="To" value="Antwerpen" />
<input type="submit" value="GO" />
</form>
<div id="map"></div>
<script type="text/javascript" src="https://maps.google.com/maps/api/js?key=YOUR_API_KEY&libraries=geometry"></script>
<script>
var map;
var directionsService;
var polylines = [];
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 50.84659376378408, lng: 4.3531406857355215},
zoom: 12,
mapTypeId: 'terrain'
});
google.maps.event.addDomListener(document.getElementById('form'), 'submit', function(e) {
calcRoute(
document.getElementById('from').value,
document.getElementById('to').value
);
// prevent the form from really submitting
e.preventDefault();
return false;
});
directionsService = new google.maps.DirectionsService();
// get the bounds of the polyline
// http://stackoverflow.com/questions/3284808/getting-the-bounds-of-a-polyine-in-google-maps-api-v3
google.maps.Polyline.prototype.getBounds = function(startBounds) {
if(startBounds) {
var bounds = startBounds;
}
else {
var bounds = new google.maps.LatLngBounds();
}
this.getPath().forEach(function(item, index) {
bounds.extend(new google.maps.LatLng(item.lat(), item.lng()));
});
return bounds;
};
}
function calcRoute(start, end) {
var request = {
origin: start,
destination: end,
provideRouteAlternatives: true,
unitSystem: google.maps.UnitSystem.METRIC,
travelMode: google.maps.TravelMode['DRIVING']
};
directionsService.route(request, function(response, status) {
// clear former polylines
for(var j in polylines ) {
polylines[j].setMap(null);
}
polylines = [];
if (status == google.maps.DirectionsStatus.OK) {
var bounds = new google.maps.LatLngBounds();
// draw the lines in reverse orde, so the first one is on top (z-index)
for(var i=response.routes.length - 1; i>=0; i-- ) {
// let's make the first suggestion highlighted;
if(i==0) {
var color = '#0000ff';
}
else {
var color = '#999999';
}
var line = drawPolyline(response.routes[i].overview_path, color);
polylines.push(line);
bounds = line.getBounds(bounds);
google.maps.event.addListener(line, 'click', function() {
// detect which route was clicked on
var index = polylines.indexOf(this);
highlightRoute(index);
});
}
map.fitBounds(bounds);
}
});
}
function highlightRoute(index) {
for(var j in polylines ) {
if(j==index) {
var color = '#0000ff';
}
else {
var color = '#999999';
}
polylines[j].setOptions({strokeColor: color});
}
}
function drawPolyline(path, color) {
var line = new google.maps.Polyline({
path: path,
strokeColor: color,
strokeOpacity: 0.7,
strokeWeight: 3
});
line.setMap(map);
return line;
}
google.maps.event.addDomListener(window, 'load', initMap);
</script>
</body>
</html>
All. I'm developing dashboard application which uses google maps API. I'm trying to render many google.maps.Polygon in a map.
Once it loads polygon data from AJAX request, I created some polygons, and I store them in array. For each loop of creating polygon,
I added google maps event to every polygon (mouseover, mouseout, and click event). It succesfully rendered all polygon on the map. But
not all polygon has event, just some of them. Would you like to give me some solutions of this problem?
Here is the part of code
function big_loadMapCells() {
var serviceUrl = './Services/example';
var currentIdx = 0;
var pagingCount = 5000;
while (currentIdx < totalCount) {
// send ajax
Ext.Ajax.request({
method: "GET",
url: serviceUrl + '?start=' + currentIdx + '&limit=' + pagingCount,
timeout: 300000,
success: function (c) {
var jsonObj = Ext.JSON.decode(c.responseText);
if (jsonObj) {
big_createCellsFromJSON(jsonObj);
}
}
});
currentIdx += pagingCount;
}
}
function big_createCellsFromJSON(jsonObj) {
// looping for creating polygon
for (var a = 0; a < jsonObj.items.length; a++) {
var cellJson = jsonObj.items[a];
var data = {
lacCi: cellJson.LACCI
tech: cellJson.TECH,
periodType: cellJson.PERIOD_TIME,
time: cellJson.DATETIME_ID,
region: cellJson.REGION,
latitude: cellJson.LATITUDE,
longitude: cellJson.LONGITUDE,
node: cellJson.NODE,
siteName: cellJson.SITE,
kpi: cellJson.KPI,
cellName: cellJson.CELL_NAME,
azimuth: cellJson.AZIMUTH,
beamWidth: width,
beamConst: radius,
color: cellJson.COLOR
};
var myCell = big_createCellPolygon(data);
big_arrCells.push(myCell);
}
}
function big_createCellPolygon(data) {
// create polygon using my own javascript, CELL object
var myCell = new CELL();
myCell.setOptions({
paths: myCell.pts,
strokeColor: myCell.color,
strokeOpacity: 0.8,
strokeWeight: 0,
fillColor: myCell.color,
fillOpacity: 0.5,
map: big_map
});
function addCellEvent(myCell) {
google.maps.event.addListener(myCell, 'mouseover', function () {
this.setOptions({
strokeWeight: 1,
fillOpacity: 0.7
});
});
google.maps.event.addListener(myCell, 'mouseout', function () {
this.setOptions({
strokeWeight: 0,
fillOpacity: 0.5
});
});
google.maps.event.addListener(myCell, 'click', function (evt) {
big_createInfoWindowCell(data, evt.latLng);
});
}
addCellEvent(myCell);
return myCell;
}
big_loadMapCells();