when I draw the last two polygons has a z-index greater than the first, so "hidden" at first and I can not choose, then what I'm trying to do is change the z-index by area
I try this
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(e) {
if (e.type != google.maps.drawing.OverlayType.MARKER) {
// Switch back to non-drawing mode after drawing a shape.
drawingManager.setDrawingMode(null);
// Add an event listener that selects the newly-drawn shape when the user
// mouses down on it.
var newShape = e.overlay;
lastPolygon = e.overlay;
newShape.type = e.type;
google.maps.event.addListener(newShape, 'click', function() {
setSelection(newShape);
});
setSelection(newShape);
}
console.log(newShape);
ArrayDeZonas.push(newShape);
zIndex += 1
ordenarZonasDescendente(ArrayDeZonas);
});
function ordenarZonasDescendente(zonas) {
var zonaAuxiliar;
for (var i = 0; i < getCantidadElementos(zonas); i++) {
for (var j = i+1; j < getCantidadElementos(zonas); j++) {
var area1 = getArea(GetGLatLngArray(zonas[i]));
var area2 = getArea(GetGLatLngArray(zonas[j]));
if (area1 < area2) {
zonas[i].zIndex = zIndex //Smaller area greater z Index
zonas[j].zIndex = zIndex-1; //Larger area less zIndexx
}
}
}
return zonas;
}
in console output
in consola.log () it shows me that their z-index changed and are fine, but not updated on the map, I'm not able to select the polygon that is inside.
Sorry for my English, I hope it is understood what I want, thank you very much!
I would suggest:
use the geometry library to compute the area
var area = google.maps.geometry.spherical.computeArea(zonas[i].getPath());
use the javascript array sort to order the polygons
zonas.sort(byArea);
function byArea(a, b) {
if (a._area < b._area) {
return -1;
}
if (a._area > b._area) {
return 1;
}
// a must be equal to b
return 0;
}
Then you can do this:
function ordenarZonasDescendente(zonas) {
for (var i = 0; i < zonas.length; i++) {
var area = google.maps.geometry.spherical.computeArea(zonas[i].getPath());
zonas[i]._area = area;
}
zonas.sort(byArea);
for (var i = 0; i < zonas.length; i++) {
zonas[i].set("zIndex", (zonas.length - i));
}
return zonas;
}
proof of concept fiddle
code snippet:
$(document).ready(function() {
function ordenarZonasDescendente(zonas) {
for (var i = 0; i < zonas.length; i++) {
var area = google.maps.geometry.spherical.computeArea(zonas[i].getPath());
zonas[i]._area = area;
}
zonas.sort(byArea);
for (var i = 0; i < zonas.length; i++) {
zonas[i].set("zIndex", (zonas.length - i));
}
return zonas;
}
function byArea(a, b) {
if (a._area < b._area) {
return -1;
}
if (a._area > b._area) {
return 1;
}
// a must be equal to b
return 0;
}
var ArrayDeZonas = [];
var zIndex = 0;
var infowindow = new google.maps.InfoWindow();
var mapHeight = '400px';
// $('#map-canvas').css('height', mapHeight);
var map = new google.maps.Map(document.getElementById('map-canvas'), {
center: {
lat: 47.53187912201915,
lng: 7.705222390807307
},
zoom: 20,
});
var map_drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: null,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_LEFT,
drawingModes: [
google.maps.drawing.OverlayType.MARKER,
google.maps.drawing.OverlayType.POLYGON
]
},
//drawingMode: google.maps.drawing.OverlayType.POLYGON,
markerOptions: {
draggable: true
},
polylineOptions: {
editable: true,
draggable: true
},
map: map
});
google.maps.event.addListener(map_drawingManager, 'overlaycomplete', function(e) {
if (e.type != google.maps.drawing.OverlayType.MARKER) {
// Switch back to non-drawing mode after drawing a shape.
map_drawingManager.setDrawingMode(null);
// Add an event listener that selects the newly-drawn shape when the user
// mouses down on it.
var newShape = e.overlay;
lastPolygon = e.overlay;
newShape.type = e.type;
google.maps.event.addListener(newShape, 'click', function(evt) {
newShape.setOptions({
draggable: true
});
infowindow.setContent("vertices: " + this.getPath().getLength() + "<br>" + "area: " + google.maps.geometry.spherical.computeArea(this.getPath()) + "<br>" + "zIndex: " + this.get("zIndex") + "<br>" + "coords: " + evt.latLng.toUrlValue(6));
infowindow.setPosition(evt.latLng);
infowindow.open(map);
/*
setSelection(newShape);
*/
});
/*
setSelection(newShape);
*/
console.log(newShape);
ArrayDeZonas.push(newShape);
zIndex += 1;
ordenarZonasDescendente(ArrayDeZonas);
}
});
})
html,
body,
#map-canvas {
height: 500px;
width: 750px;
margin: 0px;
padding: 0px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,drawing"></script>
<div id="map-canvas" style="border: 2px solid #3872ac;"></div>
Related
I am trying to get the Snap to Road demo working that is supplied here but I keep getting the error: Google Maps API error: MissingKeyMapError. I already searched around and this is the error Google gives you for either supplying no key or a invalid key but even if I generate a brand new key it won't work. It just gives me a blank screen.
Why is it throwing this error even though I supply the code with the API key?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!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="jquery-3.2.1.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=drawing,places"></script>
<script>
var apiKey = 'AIzaSyB3kpx3fgR9VT3WL2tp49QrbnyDdgygGeo';
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).on('load', function() {
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>
If you haven't got an API KEY:
The script element that loads the API is missing the required authentication parameter. If you are using the standard Maps JavaScript API, you must use a key parameter with a valid API key.
Step 1: Get a Key from this URL
https://developers.google.com/maps/documentation/javascript/get-api-key
Step 2: Include your script with the API KEY
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"
type="text/javascript"></script>
Or replace
var apiKey = 'YOUR_API_KEY';
If you got an API KEY
Google maps Snap to Road demo
Full Code
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;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Roads API Demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="/_static/js/jquery-bundle.js"></script>
<script
src="https://maps.googleapis.com/maps/api/js?libraries=drawing,places"></script>
<script>
var apiKey = 'AIzaSyB3kpx3fgR9VT3WL2tp49QrbnyDdgygGeo';
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>
EDIT: this problem is solved thanks to the help of geocodezip who pointed me the right way in the comments...
problem:
i want transit-directions from google as plain text and i need the transit_details. i tried adding all variations of stuff like (which does not work):
steps[i].transit.arrival_stop.name
solution: most transit routes have the first and last steps walking. in this case, .transit does not exist and produces the error.
i fixed the code below accordingly (which now works).
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title></title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?"></script>
</head>
<body style="font-family: Arial; font-size: 12px; color:#FFFFFF;" bgcolor="#202020">
<div id="panel" style="width: 300px; float: left;"></div>
<div id="map" style="width: 300px; height: 300px;"></div>
<script type="text/javascript">
calcRoute();
function calcRoute() {
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
});
directionsDisplay.setMap(map);
var request = {
origin: 'Potsdamer Platz, 10785 Berlin',
destination: 'Falckensteinstraße, Berlin',
travelMode: google.maps.DirectionsTravelMode.TRANSIT,
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
writeDirectionsSteps(directionsDisplay.directions.routes[0].legs[0].steps);
}
else {
console.error('DirectionsStatus is ' + status);
}
});
}
function writeDirectionsSteps(steps) {
var directions = document.getElementById('panel');
directions.innerHTML = '';
for (var i = 0; i < steps.length; i++) {
directions.innerHTML += '<br/><br/>' + steps[i].instructions + '<br/>' + steps[i].distance.text;
if (typeof steps[i].transit !== "undefined") {
directions.innerHTML += '<br/>' + steps[i].transit.arrival_stop.name;
}
}
}
</script>
</body>
</html>
(code based on: Google Maps Api v3: How to change the Default waypoint markers in the Directions (set)Panel?)
any help is appreciated a lot!
You need to code defensively. The .transit property will not be there in all the steps, only those that involve the actual transit itself (i.e. not on the walk to and from the station).
function writeDirectionsSteps(steps) {
var directions = document.getElementById('panel');
directions.innerHTML = '';
for (var i = 0; i < steps.length; i++) {
directions.innerHTML += '<br/><br/>' + steps[i].instructions + '<br/>' + steps[i].distance.text;
// if .transit property exists
if (!!steps[i].transit) {
directions.innerHTML += '<br/>' + steps[i].transit.arrival_stop.name;
}
}
}
proof of concept fiddle
code snippet:
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var routeBounds = false;
var overlayWidth = 200; // Width of the overlay DIV
var leftMargin = 30; // Grace margin to avoid too close fits on the edge of the overlay
var rightMargin = 80; // Grace margin to avoid too close fits on the right and leave space for the controls
overlayWidth += leftMargin;
var start = new google.maps.LatLng(3.148173, 101.7148792);
var end = new google.maps.LatLng(3.1347725, 101.6893408);
function initialize() {
var btn1 = document.getElementById('calcRoute');
btn1.addEventListener('click', calcRoute);
var btn2 = document.getElementById('offsetMap');
btn2.addEventListener('click', offsetMap);
var btn3 = document.getElementById('fitAndOffsetMap');
btn3.addEventListener('click', fitAndOffsetMap);
var btn4 = document.getElementById('fitMap');
btn4.addEventListener('click', fitMap);
directionsDisplay = new google.maps.DirectionsRenderer({
draggable: true
});
var mapOptions = {
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: start,
panControlOptions: {
position: google.maps.ControlPosition.TOP_RIGHT
},
zoomControlOptions: {
position: google.maps.ControlPosition.TOP_RIGHT
}
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
directionsDisplay.setMap(map);
}
function offsetMap() {
if (routeBounds !== false) {
// Clear listener defined in directions results
google.maps.event.clearListeners(map, 'idle');
// Top right corner
var topRightCorner = new google.maps.LatLng(map.getBounds().getNorthEast().lat(), map.getBounds().getNorthEast().lng());
// Top right point
var topRightPoint = fromLatLngToPoint(topRightCorner).x;
// Get pixel position of leftmost and rightmost points
var leftCoords = routeBounds.getSouthWest();
var leftMost = fromLatLngToPoint(leftCoords).x;
var rightMost = fromLatLngToPoint(routeBounds.getNorthEast()).x;
// Calculate left and right offsets
var leftOffset = (overlayWidth - leftMost);
var rightOffset = ((topRightPoint - rightMargin) - rightMost);
// Only if left offset is needed
if (leftOffset >= 0) {
if (leftOffset < rightOffset) {
var mapOffset = Math.round((rightOffset - leftOffset) / 2);
// Pan the map by the offset calculated on the x axis
map.panBy(-mapOffset, 0);
// Get the new left point after pan
var newLeftPoint = fromLatLngToPoint(leftCoords).x;
if (newLeftPoint <= overlayWidth) {
// Leftmost point is still under the overlay
// Offset map again
offsetMap();
}
} else {
// Cannot offset map at this zoom level otherwise both leftmost and rightmost points will not fit
// Zoom out and offset map again
map.setZoom(map.getZoom() - 1);
offsetMap();
}
}
}
}
function fromLatLngToPoint(latLng) {
var scale = Math.pow(2, map.getZoom());
var nw = new google.maps.LatLng(map.getBounds().getNorthEast().lat(), map.getBounds().getSouthWest().lng());
var worldCoordinateNW = map.getProjection().fromLatLngToPoint(nw);
var worldCoordinate = map.getProjection().fromLatLngToPoint(latLng);
return new google.maps.Point(Math.floor((worldCoordinate.x - worldCoordinateNW.x) * scale), Math.floor((worldCoordinate.y - worldCoordinateNW.y) * scale));
}
function calcRoute() {
var request = {
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode.TRANSIT,
transitOptions: {
departureTime: new Date("01/03/2017 9:00 AM EST")
}
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
// Define route bounds for use in offsetMap function
routeBounds = response.routes[0].bounds;
// Write directions steps
writeDirectionsSteps(response.routes[0].legs[0].steps);
// Wait for map to be idle before calling offsetMap function
google.maps.event.addListener(map, 'idle', function() {
// Offset map
offsetMap();
});
// Listen for directions changes to update bounds and reapply offset
google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
// Get the updated route directions response
var updatedResponse = directionsDisplay.getDirections();
// Update route bounds
routeBounds = updatedResponse.routes[0].bounds;
// Fit updated bounds
map.fitBounds(routeBounds);
// Write directions steps
writeDirectionsSteps(updatedResponse.routes[0].legs[0].steps);
// Offset map
offsetMap();
});
}
});
}
function writeDirectionsSteps(steps) {
var directions = document.getElementById('overlayContent');
directions.innerHTML = '';
for (var i = 0; i < steps.length; i++) {
directions.innerHTML += '<br/><br/>' + steps[i].instructions + '<br/>' + steps[i].distance.text;
// if .transit property exists
if (!!steps[i].transit) {
directions.innerHTML += '<br/>station name:' + steps[i].transit.arrival_stop.name;
}
}
}
function fitMap() {
if (routeBounds !== false) {
map.fitBounds(routeBounds);
}
}
function fitAndOffsetMap() {
if (routeBounds !== false) {
map.fitBounds(routeBounds);
offsetMap();
}
}
initialize();
body {
margin: 0;
padding: 0;
font-family: Arial;
}
#map-canvas {
height: 450px;
}
#overlay {
position: absolute;
width: 200px;
height: 450px;
background: black;
opacity: .8;
top: 0;
left: 0;
overflow: auto;
}
#overlayContent {
color: white;
padding: 10px 20px;
}
#overlayContent p {
font-size: 12px;
margin: 6px 0;
}
#overlayContent small {
display: block;
text-align: right;
font-style: italic;
}
small {
font-size: 9px;
}
i {
color: lightblue;
}
h1 {
font-size: 20px;
}
h5 {
font-size: 12px;
}
button {
margin: 20px 0 0 20px;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
<div id="map-canvas"></div>
<div id="overlay">
<div id="overlayContent">
<h1>DIV OVERLAY</h1>
<h5>Routes should not be drawn below this element.</h5>
<h5>Click the <i>Calc route</i> button to draw the directions route.</h5>
<h5><i>Map offset</i> will be applied automatically.</h5>
<h5><i>Drag the route</i> to see how it is applied.</h5>
<h5>Click the <i>Offset map</i> button to reapply the offset.</h5>
<h5>Click the <i>Fit only</i> button to only fit route bounds.</h5>
<h5>Click the <i>Fit and offset map</i> button to fit to route bounds and reapply offset.</h5>
</div>
</div>
<button id="calcRoute">Calc route</button>
<button id="offsetMap">Offset map</button>
<button id="fitMap">Fit only</button>
<button id="fitAndOffsetMap">Fit and offset map</button>
Hi i'm using google map marker icon with text using google chart API https://chart.googleapis.com/chart?chst=d_bubble_text_small&chld=bbT|27.b|f4b605|0f3276
in my maps the icon is not fixed if text is too long how to fixed it
this is my js code :
<script type="text/javascript">
/* <![CDATA[ */
var CITY_MAP_CENTER_LAT = -6.3757701;
var CITY_MAP_CENTER_LNG = 105.7814325;
var CITY_MAP_ZOOMING_FACT = 9;
var infowindow;
/**
* Data for the markers consisting of a name, a LatLng and a pin image, message box content for
* the order in which these markers should display on top of each
* other.
*/
var markers = {
'jalanluarkota':[
{
'name':'KOLELET - RANGKASBITUNG',
'location': [-6.338283,106.257433],
'message':'<a href="http://localhost:7777/simonitoring/laporan/laporanruasjalandetail/1" class=ptitle>KOLELET - RANGKASBITUNG</a><br/><span class=ptiming>Status: Jalan Luar Kota</span></br><span class=ptiming>Panjang Ruas (Km): 5.30</span></br><span class=ptiming>Paket Pekerjaan: 1</span>',
'icons':'https://chart.googleapis.com/chart?chst=d_bubble_text_small&chld=bbT|1|f4b605|0f3276'
},
]};
var map = null;
var mgr = null;
var mc = null;
var markerClusterer = null;
var showMarketManager = false;
if(CITY_MAP_CENTER_LAT=='')
{
var CITY_MAP_CENTER_LAT = 34;
}
if(CITY_MAP_CENTER_LNG=='')
{
var CITY_MAP_CENTER_LNG = 0;
}
if(CITY_MAP_CENTER_LAT!='' && CITY_MAP_CENTER_LNG!='' && CITY_MAP_ZOOMING_FACT =='')
{
var CITY_MAP_ZOOMING_FACT = 9;
}
else if(CITY_MAP_ZOOMING_FACT == '')
{
var CITY_MAP_ZOOMING_FACT = 3;
}
var PIN_POINT_ICON_HEIGHT = 37;
var PIN_POINT_ICON_WIDTH = 32;
if(MAP_DISABLE_SCROLL_WHEEL_FLAG)
{
var MAP_DISABLE_SCROLL_WHEEL_FLAG = 'No';
}
function setCategoryVisiblity( category, visible ) {
var i;
if ( mgr && category in markers ) {
for( i = 0; i < markers[category].length; i += 1 ) {
if ( visible ) {
mgr.addMarker( markers[category][i], 0 );
} else {
mgr.removeMarker( markers[category][i], 0 );
}
}
mgr.refresh();
}
}
function initialize() {
var myOptions = {
zoom: CITY_MAP_ZOOMING_FACT,
center: new google.maps.LatLng(CITY_MAP_CENTER_LAT, CITY_MAP_CENTER_LNG),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_luarkota"),myOptions);
mgr = new MarkerManager( map );
google.maps.event.addListener(mgr, 'loaded', function() {
if (markers) {
var k = 0;
for (var level in markers) {
google.maps.event.addDomListener( document.getElementById( level ), 'click', function() {
setCategoryVisiblity( this.id, this.checked );
});
for (var i = 0; i < markers[level].length; i++) {
var details = markers[level][i];
var image = new google.maps.MarkerImage(details.icons,new google.maps.Size(PIN_POINT_ICON_WIDTH, PIN_POINT_ICON_HEIGHT));
var myLatLng = new google.maps.LatLng(details.location[0], details.location[1]);
markers[level][i] = new google.maps.Marker({
title: details.name,
position: myLatLng,
icon: image,
clickable: true,
draggable: false,
flat: true
});
attachMessage(markers[level][i], details.message);
}
mgr.addMarkers( markers[level], 0 );
}
mgr.refresh();
}
});
// but that message is not within the marker's instance data
function attachMessage(marker, msg) {
var myEventListener = google.maps.event.addListener(marker, 'click', function() {
if (infowindow) infowindow.close();
infowindow = new google.maps.InfoWindow({
content: String(msg)
});
infowindow.open(map,marker);
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
/* ]]> */
</script>
how to fixed that thanks...
My requirement is, need to show all Transit Bus stations of a particular location(like state, city) and should able to mark only transit bus stations and show the infoWindow of that Transit Bus station using google map javascript api.
below is my html code, javascript marker logic also marks all the locations on the map i need to mark only transit bus stations
<!DOCTYPE html>
<html>
<head>
<title>Add/Remove Markers</title>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 50%;
width:50%;
position:inherit !important;
margin-top:50px !important;
}
#floating-panel {
position: absolute;
top: 10px;
left: 25%;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
text-align: center;
font-family: 'Roboto','sans-serif';
line-height: 30px;
padding-left: 10px;
}
#map > div{
height:70% !important;
width:70% !important;
margin-top:50px !important;
}
a[href^="https://maps.google.com/maps"]{
display: none !important;
}
.gmnoprint a, .gmnoprint span, .gm-style-cc div {
display: none !important;
}
.gmnoprint div {
background: none !important;
}
</style>
</head>
<body>
<div id="floating-panel">
<input onclick="clearMarkers();" type=button value="Hide Markers">
<input onclick="showMarkers();" type=button value="Show All Markers">
<input onclick="deleteMarkers();" type=button value="Delete Markers">
</div>
<div id="map"></div>
<p>Click on the map to add markers.</p>
<script>
// In the following example, markers appear when the user clicks on the map.
// The markers are stored in an array.
// The user can then click an option to hide, show or delete the markers.
var map;
var markers = [];
function initMap() {
var haightAshbury = {lat: 37.769, lng: -122.446};
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: haightAshbury,
disableDefaultUI: true
});
// This event listener will call addMarker() when the map is clicked.
map.addListener('click', function (event) {
addMarker(event.latLng);
});
// Adds a marker at the center of the map.
addMarker(haightAshbury);
}
// 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);
//This code is to remove the marker from the map and the array
marker.addListener('click', function (e) {
var latIndex = markers.findIndex(x=>x.position.lat() == e.latLng.lat());
var lngIndex = markers.findIndex(x=>x.position.lng() == e.latLng.lng());
if ((latIndex != -1 && lngIndex != -1) && (latIndex == lngIndex)) {
markers[latIndex].setMap(null); // To remove the marker from the Map
markers.splice(latIndex, 1); // to remove the marker from the list of array
}
});
marker.addListener('mouseover', function (e) {
infowindow.open(map, this);
});
// assuming you also want to hide the infowindow when user mouses-out
marker.addListener('mouseout', function (e) {
infowindow.close();
});
}
// 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);
}
// Shows any markers currently in the array.
function showMarkers() {
setMapOnAll(map);
}
// Deletes all markers in the array by removing references to them.
function deleteMarkers() {
clearMarkers();
markers = [];
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=APIKEY&callback=initMap">
</script>
</body>
</html>
var map;
var infowindow;
var service;
var markers = [];
var availableMarkers = [];
var unAvailableMarkers = [];
var selectedMarkers = [];
var globalResults = [];
function initialize(lat,lng)
{
var origin = new google.maps.LatLng(lat,lng);
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: origin,
zoom: 15,
disableDefaultUI: true
});
var request = {
location: origin,
radius: 2500,
types: ['bus_station']
};
infowindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map);
service.search(request, callback);
map.addListener('click', function (event) {
initialize(event.latLng.lat(), event.latLng.lng())
});
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
globalResults = results;
for (var i = 0; i < results.length; i++) {
if (i < 11)
createMarker(results[i], 'green');
else
createMarker(results[i], 'red');
}
}
}
function createMarker(place,color) {
var placeLoc = place.geometry.location;
var icon;
if (color == 'green')
icon = 'http://maps.google.com/mapfiles/ms/icons/green-dot.png';
else if (color == 'red')
icon = 'http://maps.google.com/mapfiles/ms/icons/red-dot.png';
else
icon = 'http://maps.google.com/mapfiles/ms/icons/yellow-dot.png';
resizeIcon = icon;
var marker = null;
if (color == 'green') {
marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon: resizeIcon
});
availableMarkers.push(marker);
}
else if (color == 'red') {
marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon: resizeIcon
});
unAvailableMarkers.push(marker);
}
else {
marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon: resizeIcon
});
selectedMarkers.push(marker);
}
markers.push(marker);
var content = '<div><strong>' + place.name + '</strong><br>' +
'Place ID: ' + place.place_id;
var more_content = '<img src="../Content/Images/1475150806_map-marker.png"/>'; // this is to show the image r any additional content
//make a request for further details
service.getDetails({ reference: place.reference }, function (place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
more_content = '<hr/><strong>Details';
if (place.website) {
more_content += '<br/><br/><strong>' + place.website + '';
}
}
});
google.maps.event.addListener(marker, 'mouseover', function () {
//infowindow.setContent(content + more_content);
infowindow.setContent(content);
infowindow.open(map, this);
});
// assuming you also want to hide the infowindow when user mouses-out
//google.maps.event.addListener(marker, 'mouseout', function (e) {
// infowindow.close();
//});
google.maps.event.addListener(marker, 'click', function (e) {
var latIndex = markers.findIndex(x=>x.position.lat() == e.latLng.lat());
var lngIndex = markers.findIndex(x=>x.position.lng() == e.latLng.lng());
var isAvailLat = availableMarkers.findIndex(x=>x.position.lat() == e.latLng.lat());
var isAvailLng = availableMarkers.findIndex(x=>x.position.lng() == e.latLng.lng());
var isUnAvailLat = unAvailableMarkers.findIndex(x=>x.position.lat() == e.latLng.lat());
var isUnAvailLng = unAvailableMarkers.findIndex(x=>x.position.lng() == e.latLng.lng());
var isSelectedLat = selectedMarkers.findIndex(x=>x.position.lat() == e.latLng.lat());
var isSelectedLng = selectedMarkers.findIndex(x=>x.position.lng() == e.latLng.lng());
if ((latIndex != -1 && lngIndex != -1) && (latIndex == lngIndex)) {
if ((isSelectedLat != -1 && isSelectedLng != -1) && (isSelectedLat == isSelectedLng)) {
selectedMarkers.splice(isSelectedLat, 1);
availableMarkers.push(markers[latIndex]);
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png');
}
else if ((isAvailLat != -1 && isAvailLng != -1) && (isAvailLat == isAvailLng)) {
availableMarkers.splice(isAvailLat, 1);
selectedMarkers.push(markers[latIndex]);
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/yellow-dot.png');
}
else if ((isUnAvailLat != -1 && isUnAvailLng != -1) && (isUnAvailLat == isUnAvailLng)) {
alert('This Transit is not avaliable, pls select a valid transit');
}
}
});
}
google.maps.event.addDomListener(window, 'load', function () { initialize(39.759444, -84.191667); });
/*These styles area added to hide the google footer*/
a[href^="http://maps.google.com/maps"] {
display: none !important;
}
a[href^="https://maps.google.com/maps"] {
display: none !important;
}
.gmnoprint a, .gmnoprint span, .gm-style-cc {
display: none;
}
.gmnoprint div {
background: none !important;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Transit</title>
</head>
<body>
<div id="map" style="height:600px;"></div>
<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places"></script>
</body>
</html>
Customs icons were working on my google maps ( with KML file ) but they disappeared. I read the related post on stackoverflow but since I have not already used <color/> what can I do on my map ?
You can see the example page here and the script is as below:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="http://geoxml3.googlecode.com/svn/branches/kmz/ZipFile.complete.js">
</script>
<script type="text/javascript" src="http://geoxml3.googlecode.com/svn/branches/kmz/geoxml3.js">
</script>
<script type="text/javascript" src="http://geoxml3.googlecode.com/svn/trunk/ProjectedOverlay.js">
</script>
<script type="text/javascript">
var geoXml = null;
var geoXmlDoc = null;
var map = null;
var myLatLng = null;
var myGeoXml3Zoom = true;
var sidebarHtml = "";
var infowindow = null;
var kmlLayer = null;
var filename = "footballteams-uk.xml";
function MapTypeId2UrlValue(maptype) {
var urlValue = 'm';
switch(maptype){
case google.maps.MapTypeId.HYBRID: urlValue='h';
break;
case google.maps.MapTypeId.SATELLITE: urlValue='k';
break;
case google.maps.MapTypeId.TERRAIN: urlValue='t';
break;
default:
case google.maps.MapTypeId.ROADMAP: urlValue='m';
break;
}
return urlValue;
}
function initialize() {
myLatLng = new google.maps.LatLng(52.82,-1.63);
// these set the initial center, zoom and maptype for the map
// if it is not specified in the query string
var lat = 52.82;
var lng = -1.63;
var zoom = 7;
var maptype = google.maps.MapTypeId.TERRAIN;
// If there are any parameters at eh end of the URL, they will be in location.search
// looking something like "?marker=3"
// skip the first character, we are not interested in the "?"
var query = location.search.substring(1);
// split the rest at each "&" character to give a list of "argname=value" pairs
var pairs = query.split("&");
for (var i=0; i<pairs.length; i++) {
// break each pair at the first "=" to obtain the argname and value
var pos = pairs[i].indexOf("=");
var argname = pairs[i].substring(0,pos).toLowerCase();
var value = pairs[i].substring(pos+1).toLowerCase();
// process each possible argname - use unescape() if theres any chance of spaces
if (argname == "id") {id = unescape(value);}
if (argname == "filename") {filename = unescape(value);}
if (argname == "marker") {index = parseFloat(value);}
if (argname == "lat") {lat = parseFloat(value);}
if (argname == "lng") {lng = parseFloat(value);}
if (argname == "zoom") {
zoom = parseInt(value);
myGeoXml3Zoom = false;
}
if (argname == "type") {
// from the v3 documentation 8/24/2010
// HYBRID This map type displays a transparent layer of major streets on satellite images.
// ROADMAP This map type displays a normal street map.
// SATELLITE This map type displays satellite images.
// TERRAIN This map type displays maps with physical features such as terrain and vegetation.
if (value == "m") {maptype = google.maps.MapTypeId.ROADMAP;}
if (value == "k") {maptype = google.maps.MapTypeId.SATELLITE;}
if (value == "h") {maptype = google.maps.MapTypeId.HYBRID;}
if (value == "t") {maptype = google.maps.MapTypeId.TERRAIN;}
}
}
if (!isNaN(lat) && !isNaN(lng)) {
myLatLng = new google.maps.LatLng(lat, lng);
}
var myOptions = {
zoom: zoom,
center: myLatLng,
// zoom: 5,
// center: myLatlng,
mapTypeId: maptype
};
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
infowindow = new google.maps.InfoWindow({});
//adsense start
var adUnitDiv = document.createElement('div');
var adUnitOptions = { format: google.maps.adsense.AdFormat.LEADERBOARD,
position: google.maps.ControlPosition.BOTTOM,
backgroundColor: '#FFFF33',
borderColor: '#e5ecf9',
titleColor: '#0000cc',
textColor: '#000000',
urlColor: '#009900',
map: map,
visible: true,
publisherId: 'pub-3506441846587527',
channelNumber:'4940650139'
}
adUnit = new google.maps.adsense.AdUnit(adUnitDiv, adUnitOptions);
//adsense end
geoXml = new geoXML3.parser({
map: map,
zoom: myGeoXml3Zoom,
infoWindow: infowindow,
singleInfoWindow: true,
afterParse: useTheData
});
geoXml.parse(filename);
google.maps.event.addListener(map, "bounds_changed", makeSidebar);
google.maps.event.addListener(map, "center_changed", makeSidebar);
google.maps.event.addListener(map, "zoom_changed", makeSidebar);
// Make the link the first time when the page opens
makeLink();
// Make the link again whenever the map changes
google.maps.event.addListener(map, 'maptypeid_changed', makeLink);
google.maps.event.addListener(map, 'center_changed', makeLink);
google.maps.event.addListener(map, 'bounds_changed', makeLink);
google.maps.event.addListener(map, 'zoom_changed', makeLink);
};
function kmlPgClick(pm) {
if (geoXml.docs[0].placemarks[pm].polygon.getMap()) {
google.maps.event.trigger(geoXmlDoc.placemarks[pm].polygon,"click");
} else {
geoXmlDoc.placemarks[pm].polygon.setMap(map);
google.maps.event.trigger(geoXmlDoc.placemarks[pm].polygon,"click");
}
}
function kmlPlClick(pm) {
if (geoXml.docs[0].placemarks[pm].polyline.getMap()) {
google.maps.event.trigger(geoXmlDoc.placemarks[pm].polyline,"click");
} else {
geoXmlDoc.placemarks[pm].polyline.setMap(map);
google.maps.event.trigger(geoXmlDoc.placemarks[pm].polyline,"click");
}
}
function kmlClick(pm) {
if (geoXml.docs[0].placemarks[pm].marker.getMap()) {
google.maps.event.trigger(geoXml.docs[0].placemarks[pm].marker,"click");
} else {
geoXmlDoc.placemarks[pm].marker.setMap(map);
google.maps.event.trigger(geoXmlDoc.placemarks[pm].marker,"click");
}
}
function kmlShowPlacemark(pm) {
if (geoXmlDoc.placemarks[pm].polygon) {
map.fitBounds(geoXmlDoc.placemarks[pm].polygon.bounds);
} else if (geoXmlDoc.placemarks[pm].polyline) {
map.fitBounds(geoXmlDoc.placemarks[pm].polyline.bounds);
} else if (geoXmlDoc.placemarks[pm].marker) {
map.setCenter(geoXmlDoc.placemarks[pm].marker.getPosition());
}
for (var i=0;i<geoXmlDoc.placemarks.length;i++) {
var placemark = geoXmlDoc.placemarks[i];
if (i == pm) {
if (placemark.polygon) placemark.polygon.setMap(map);
if (placemark.polyline) placemark.polyline.setMap(map);
if (placemark.marker) placemark.marker.setMap(map);
} else {
if (placemark.polygon) placemark.polygon.setMap(null);
if (placemark.polyline) placemark.polyline.setMap(null);
if (placemark.marker) placemark.marker.setMap(null);
}
}
}
function showAll() {
map.fitBounds(geoXmlDoc.bounds);
for (var i=0;i<geoXmlDoc.placemarks.length;i++) {
var placemark = geoXmlDoc.placemarks[i];
if (placemark.polygon) placemark.polygon.setMap(map);
if (placemark.polyline) placemark.polyline.setMap(map);
if (placemark.marker) placemark.marker.setMap(map);
}
}
// == rebuilds the sidebar to match the markers currently displayed ==
function makeSidebarPolygonEntry(i) {
var name = geoXmlDoc.placemarks[i].name;
if (!name || (name.length == 0)) name = "polygon #"+i;
// alert(name);
sidebarHtml += '<tr id="row'+i+'"><td onmouseover="kmlHighlightPoly('+i+');" onmouseout="kmlUnHighlightPoly('+i+');">'+name+' - show</td></tr>';
}
function makeSidebarPolylineEntry(i) {
var name = geoXmlDoc.placemarks[i].name;
if (!name || (name.length == 0)) name = "polyline #"+i;
// alert(name);
sidebarHtml += '<tr id="row'+i+'"><td onmouseover="kmlHighlightPoly('+i+');" onmouseout="kmlUnHighlightPoly('+i+');">'+name+' - show</td></tr>';
}
function makeSidebarEntry(i) {
var name = geoXmlDoc.placemarks[i].name;
if (!name || (name.length == 0)) name = "marker #"+i;
// alert(name);
sidebarHtml += '<tr id="row'+i+'"><td>'+name+'</td></tr>';
}
function makeSidebar() {
sidebarHtml = '<table><tr><td>SHOW ALL CLUBS</td></tr>';
var currentBounds = map.getBounds();
// if bounds not yet available, just use the empty bounds object;
if (!currentBounds) currentBounds=new google.maps.LatLngBounds();
if (geoXmlDoc) {
for (var i=0; i<geoXmlDoc.placemarks.length; i++) {
if (geoXmlDoc.placemarks[i].polygon) {
if (currentBounds.intersects(geoXmlDoc.placemarks[i].polygon.bounds)) {
makeSidebarPolygonEntry(i);
}
}
if (geoXmlDoc.placemarks[i].polyline) {
if (currentBounds.intersects(geoXmlDoc.placemarks[i].polyline.bounds)) {
makeSidebarPolylineEntry(i);
}
}
if (geoXmlDoc.placemarks[i].marker) {
if (currentBounds.contains(geoXmlDoc.placemarks[i].marker.getPosition())) {
makeSidebarEntry(i);
}
}
}
}
sidebarHtml += "</table>";
document.getElementById("sidebar").innerHTML = sidebarHtml;
}
function useTheData(doc){
var currentBounds = map.getBounds();
if (!currentBounds) currentBounds=new google.maps.LatLngBounds();
// Geodata handling goes here, using JSON properties of the doc object
sidebarHtml = '<table><tr><td>Show All</td></tr>';
// var sidebarHtml = '<table>';
geoXmlDoc = doc[0];
for (var i = 0; i < geoXmlDoc.placemarks.length; i++) {
// console.log(doc[0].markers[i].title);
var placemark = geoXmlDoc.placemarks[i];
if (placemark.polygon) {
if (currentBounds.intersects(placemark.polygon.bounds)) {
makeSidebarPolygonEntry(i);
}
var normalStyle = {
strokeColor: placemark.polygon.get('strokeColor'),
strokeWeight: placemark.polygon.get('strokeWeight'),
strokeOpacity: placemark.polygon.get('strokeOpacity'),
fillColor: placemark.polygon.get('fillColor'),
fillOpacity: placemark.polygon.get('fillOpacity')
};
placemark.polygon.normalStyle = normalStyle;
highlightPoly(placemark.polygon, i);
}
if (placemark.polyline) {
if (currentBounds.intersects(placemark.polyline.bounds)) {
makeSidebarPolylineEntry(i);
}
var normalStyle = {
strokeColor: placemark.polyline.get('strokeColor'),
strokeWeight: placemark.polyline.get('strokeWeight'),
strokeOpacity: placemark.polyline.get('strokeOpacity')
};
placemark.polyline.normalStyle = normalStyle;
highlightPoly(placemark.polyline, i);
}
if (placemark.marker) {
if (currentBounds.contains(placemark.marker.getPosition())) {
makeSidebarEntry(i);
}
}
/* doc[0].markers[i].setVisible(false); */
}
sidebarHtml += "</table>";
document.getElementById("sidebar").innerHTML = sidebarHtml;
};
</script>