google map viewport auto adjust - google-maps-api-3

I found something nice animated route created by #Chad Killingsworth in this jsfiddle,i just want to ask if it is possible to adjust automatically the viewport of the map so that we can see route where it is headed.
function initialize() {
var mapOptions = {
zoom: 14,
center: new google.maps.LatLng("54.32216667","10.16530167"),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var path_start = new Array();
var path_end = new Array();
path_start.push(new google.maps.LatLng("54.32216667","10.16530167"));
path_end.push(new google.maps.LatLng("54.32216667","10.16530167"));
// lots of other points
path_start.push(new google.maps.LatLng("54.36457667","10.12173333"));
path_end.push(new google.maps.LatLng("54.36457833","10.121745"));
var carPolyline = new google.maps.Polyline({
map: map,
geodesic : true,
strokeColor : '#FF0000',
strokeOpacity : 1.0,
strokeWeight : 2
});
var carPath = new google.maps.MVCArray();
for ( var i = 0; i < path_start.length; i++) {
if(i === 0) {
carPath.push(path_start[i]);
carPolyline.setPath(carPath);
} else {
setTimeout((function(latLng) {
return function() {
carPath.push(latLng);
};
})(path_start[i]), 100 * i);
}
}
Thank you in advance.

Add:
map.setCenter(latLng);
to the code that is drawing the polyline.
var carPath = new google.maps.MVCArray();
for ( var i = 0; i < path_start.length; i++) {
if(i === 0) {
carPath.push(path_start[i]);
carPolyline.setPath(carPath);
} else {
setTimeout((function(latLng) {
return function() {
carPath.push(latLng);
map.setCenter(latLng);
};
})(path_start[i]), 100 * i);
}
}
updated fiddle

Related

How to draw different coloured polylines with direction service with snap to road feature

I am trying to render bus routes of bangalore city with snap to road feature provided by google api. If I just render single route, it is visible with the colour I mention for stroke color property of polyline.If the route is pretty long, then I am splitting the route into multiple paths for that route. But, when I add the second route, a polyline from the end of first route to the start of second route is drawn. I am not able to figure out, where I am going wrong. Any help is deeply appreciated. Please find the javascript code of the same.
<script type="text/javascript">
var infoWindow = new google.maps.InfoWindow();
var routePath;
var OrgDest;
var OrgDestpoints;
var wp;
var waypts;
var traceroutePath;
var service;
var map;
var marker, markloc;
var markers = [];
var orgdest = {"1": [[12.9197565816171, 77.5923588994416,12.95719452, 77.56829549],[12.95719452, 77.56829549,12.98997477, 77.57209867],[12.98997477, 77.57209867,13.02311, 77.55029]],"KHC": [[12.97466107, 77.58199613,12.97466107, 77.58199613]]};
var waypoints = {"1":[[12.92268932, 77.59338455,12.92318598, 77.58877168,12.9279596, 77.58760419,12.93610683, 77.58392363,12.93672057, 77.57217014,12.93956243, 77.57215225,12.94189, 77.57358,12.94574241, 77.57070059],[12.95850855, 77.57402561,12.96161187, 77.57527904,12.96366, 77.56843,12.96811874, 77.56800682,12.97736, 77.57074,12.98997477, 77.57209867],[12.98997477, 77.57209867,12.99789013, 77.57130999,13.00908169, 77.5710476,13.01742075, 77.55707759]],"KHC": [[12.98420536, 77.59761828,12.98368012, 77.6035693]]};
var routeColors = {"1": "#FF00FF","KHC": "#800000"};
var routeNames = ["1","KHC"];
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(12.9536775, 77.5883784),
zoom: 12
};
map = new google.maps.Map(document.getElementById("map-canvas"),mapOptions);
//directionsDisplay.setMap(map);
var routeInfoWindow = new google.maps.InfoWindow({ // this info window shows the route name when the mouse hovers over a route line
disableAutoPan: true
});
for (var i = 0; i < routeNames.length; i++) { // loop over each route
var routeName = routeNames[i];
for (var j = 0; j < orgdest[routeName].length; j++) { // loop over each path on the route
OrgDest = orgdest[routeName][j];
OrgDestpoints = []
for (var k = 0; k < OrgDest.length; k += 2) { // loop over each point in the path
OrgDestpoints.push(new google.maps.LatLng(OrgDest[k], OrgDest[k+1]));
}
waypts = [];
if(waypoints[routeName].length > 0)
{
wp = waypoints[routeName][j];
for (var k = 0; k < wp.length; k += 2) { // loop over each waypoints in the path
waypts.push(
{location:new google.maps.LatLng(wp[k], wp[k+1]),
stopover:true
});
}
}
if(j>0)// & (j!=(orgdest[routeName].length)))
traceroutePath.setMap(null); //clearing previously rendered map
if(i>0 & j==0)
{
traceroutePath.setMap(null); //clearing previously rendered map
}
routePath = OrgDestpoints;
traceroutePath = new google.maps.Polyline({
path: routePath,
strokeColor: routeColors[routeName],
strokeOpacity: 1.0,
strokeWeight: 2
});
service = new google.maps.DirectionsService(),traceroutePath,snap_path=[];
traceroutePath.setMap(map);
for(z=0;z<routePath.length-1;z++){
service.route({origin: routePath[z],destination: routePath[z+1],
travelMode: google.maps.DirectionsTravelMode.DRIVING,
waypoints: waypts},
function(result, status) {
if(status == google.maps.DirectionsStatus.OK) {
snap_path = snap_path.concat(result.routes[0].overview_path);
alert(result.routes[0].legs[0].start_location)
traceroutePath.setPath(snap_path);
} else alert("Directions request failed: "+status);
});
}
} //end of j for loop; paths to form a route
}//end of i for loop; all routes
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
You have two issues that are causing the issue.
the code is concatenating the paths from the directions requests together, that is an issue because:
a. the directions service is asynchronous, the routes may come back in a different order than you send them (unless you send them one by one).
b. the routes requested are not continuous.
for (z = 0; z < routePath.length - 1; z++) {
service.route({
origin: routePath[z],
destination: routePath[z + 1],
travelMode: google.maps.DirectionsTravelMode.DRIVING,
waypoints: waypts
},
function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
var snap_path = result.routes[0].overview_path;
var traceroutePath = new google.maps.Polyline({
strokeColor: routeColors[routeName],
strokeOpacity: 1.0,
strokeWeight: 2,
map: map
});
traceroutePath.setPath(snap_path);
} else alert("Directions request failed: " + status);
});
proof of concept fiddle
code snippet:
var infoWindow = new google.maps.InfoWindow();
var routePath;
var OrgDest;
var OrgDestpoints;
var wp;
var waypts;
var traceroutePath;
var service;
var map;
var marker, markloc;
var markers = [];
var orgdest = {
"1": [
[12.9197565816171, 77.5923588994416, 12.95719452, 77.56829549],
[12.95719452, 77.56829549, 12.98997477, 77.57209867],
[12.98997477, 77.57209867, 13.02311, 77.55029]
],
"KHC": [
[12.97466107, 77.58199613, 12.97466107, 77.58199613]
]
};
var waypoints = {
"1": [
[12.92268932, 77.59338455, 12.92318598, 77.58877168, 12.9279596, 77.58760419, 12.93610683, 77.58392363, 12.93672057, 77.57217014, 12.93956243, 77.57215225, 12.94189, 77.57358, 12.94574241, 77.57070059],
[12.95850855, 77.57402561, 12.96161187, 77.57527904, 12.96366, 77.56843, 12.96811874, 77.56800682, 12.97736, 77.57074, 12.98997477, 77.57209867],
[12.98997477, 77.57209867, 12.99789013, 77.57130999, 13.00908169, 77.5710476, 13.01742075, 77.55707759]
],
"KHC": [
[12.98420536, 77.59761828, 12.98368012, 77.6035693]
]
};
var routeColors = {
"1": "#FF00FF",
"KHC": "#800000"
};
var routeNames = ["1", "KHC"];
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(12.9536775, 77.5883784),
zoom: 12
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
var routeInfoWindow = new google.maps.InfoWindow({ // this info window shows the route name when the mouse hovers over a route line
disableAutoPan: true
});
for (var i = 0; i < routeNames.length; i++) { // loop over each route
var routeName = routeNames[i];
for (var j = 0; j < orgdest[routeName].length; j++) { // loop over each path on the route
OrgDest = orgdest[routeName][j];
OrgDestpoints = []
for (var k = 0; k < OrgDest.length; k += 2) { // loop over each point in the path
OrgDestpoints.push(new google.maps.LatLng(OrgDest[k], OrgDest[k + 1]));
}
waypts = [];
if (waypoints[routeName].length > 0) {
wp = waypoints[routeName][j];
for (var k = 0; k < wp.length; k += 2) { // loop over each waypoints in the path
waypts.push({
location: new google.maps.LatLng(wp[k], wp[k + 1]),
stopover: true
});
}
}
if (j > 0) // & (j!=(orgdest[routeName].length)))
traceroutePath.setMap(null); //clearing previously rendered map
if (i > 0 & j == 0) {
traceroutePath.setMap(null); //clearing previously rendered map
}
routePath = OrgDestpoints;
traceroutePath = new google.maps.Polyline({
path: routePath,
strokeColor: routeColors[routeName],
strokeOpacity: 1.0,
strokeWeight: 2
});
service = new google.maps.DirectionsService(), traceroutePath, snap_path = [];
traceroutePath.setMap(map);
for (z = 0; z < routePath.length - 1; z++) {
service.route({
origin: routePath[z],
destination: routePath[z + 1],
travelMode: google.maps.DirectionsTravelMode.DRIVING,
waypoints: waypts
},
function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
var snap_path = result.routes[0].overview_path;
var traceroutePath = new google.maps.Polyline({
strokeColor: routeColors[routeName],
strokeOpacity: 1.0,
strokeWeight: 2,
map: map
});
traceroutePath.setPath(snap_path);
} else alert("Directions request failed: " + status);
});
}
} //end of j for loop; paths to form a route
} //end of i for loop; all routes
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map-canvas"></div>

I could not delete polygon when marker is click

I am trying to delete a polygon when my marker is being clicked,but i could not get how to make this work that the polygon will be deleted.I appreciate someone will help me to make this work.
This my demo in jsfiddle.
Demo
here is my code it's not working.
var map;
var count = 0;
var polycolor = '#ED1B24';
var polyarray = [];
var marker;
var markers = [];
var path = new google.maps.MVCArray;
function initialize() {
var initial = new google.maps.LatLng(53.199246241276875, -105.76864242553711);
var mapOptions = {
zoom: 16,
center: initial,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE
},
mapTypeControl: false
};
poly.setPaths(new google.maps.MVCArray([path]));
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
google.maps.event.addListener(map, 'click', function (e) {
addMarker(e);
addPolygon(e);
});
}
var deletepolygon = function (pt) {
i = 0;
var thepath = poly.getPath();
thepath.forEach(function (ltlng) {
i++;
if ((ltlng.lat() + "," + ltlng.lng()) == pt) {
path.removeAt(i);
}
});
}

markers places are incorrect in KML google map

I made a map on Google Maps, I downloaded the KML file and used it in a map with sidebar. But the places of the markers are incorrect. All of them are below the correct places. The code is as below. Example page is on test page .If I use the simple KML layer example of Google, same errors occur.
<style type="text/css">
html, body, #map_canvas {
width: 750px;
height: 600px;
margin: 0;
padding: 0;
}
.infowindow * {font-size: 90%; margin: 0}
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript" src="http://geoxml3.googlecode.com/svn/branches/polys/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 = "europeancapitals.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;
}
// ========== This function will create the "link to this page"
function makeLink() {
// var a="http://www.geocodezip.com/v3_MW_example_linktothis.html"
var url = window.location.pathname;
var a = url.substring(url.lastIndexOf('/')+1)
+ "?lat=" + map.getCenter().lat().toFixed(6)
+ "&lng=" + map.getCenter().lng().toFixed(6)
+ "&zoom=" + map.getZoom()
+ "&type=" + MapTypeId2UrlValue(map.getMapTypeId());
if (filename != "europeancapitals.xml") a += "&filename="+filename;
document.getElementById("link").innerHTML = '<a href="' +a+ '">Link to this page<\/a>';
}
function initialize() {
myLatLng = new google.maps.LatLng(46,14);
// these set the initial center, zoom and maptype for the map
// if it is not specified in the query string
var lat = 46;
var lng = 14;
var zoom = 8;
var maptype = google.maps.MapTypeId.ROADMAP;
// 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({});
geoXml = new geoXML3.parser({
map: map,
infoWindow: infowindow,
singleInfoWindow: true,
zoom: myGeoXml3Zoom,
markerOptions: {optimized: false},
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);
}
}
}
var highlightOptions = {fillColor: "#FFFF00", strokeColor: "#000000", fillOpacity: 0.9, strokeWidth: 10};
var highlightLineOptions = {strokeColor: "#FFFF00", strokeWidth: 10};
function kmlHighlightPoly(pm) {
for (var i=0;i<geoXmlDoc.placemarks.length;i++) {
var placemark = geoXmlDoc.placemarks[i];
if (i == pm) {
if (placemark.polygon) placemark.polygon.setOptions(highlightOptions);
if (placemark.polyline) placemark.polyline.setOptions(highlightLineOptions);
} else {
if (placemark.polygon) placemark.polygon.setOptions(placemark.polygon.normalStyle);
if (placemark.polyline) placemark.polyline.setOptions(placemark.polyline.normalStyle);
}
}
}
function kmlUnHighlightPoly(pm) {
for (var i=0;i<geoXmlDoc.placemarks.length;i++) {
if (i == pm) {
var placemark = geoXmlDoc.placemarks[i];
if (placemark.polygon) placemark.polygon.setOptions(placemark.polygon.normalStyle);
if (placemark.polyline) placemark.polyline.setOptions(placemark.polyline.normalStyle);
}
}
}
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);
}
}
function highlightPoly(poly, polynum) {
// poly.setOptions({fillColor: "#0000FF", strokeColor: "#0000FF", fillOpacity: 0.3}) ;
google.maps.event.addListener(poly,"mouseover",function() {
var rowElem = document.getElementById('row'+polynum);
if (rowElem) rowElem.style.backgroundColor = "#FFFA5E";
if (geoXmlDoc.placemarks[polynum].polygon) {
poly.setOptions(highlightOptions);
} else if (geoXmlDoc.placemarks[polynum].polyline) {
poly.setOptions(highlightLineOptions);
}
});
google.maps.event.addListener(poly,"mouseout",function() {
var rowElem = document.getElementById('row'+polynum);
if (rowElem) rowElem.style.backgroundColor = "#FFFFFF";
poly.setOptions(poly.normalStyle);
});
}
// == 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</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;
};
function hide_kml(){
geoXml.hideDocument();
}
function unhide_kml(){
geoXml.showDocument();
}
function reload_kml(){
geoXml.hideDocument();
delete geoXml;
geoXml = new geoXML3.parser({
map: map,
singleInfoWindow: true,
afterParse: useTheData
});
geoXml.parse(filename);
}
function hide_markers_kml(){
for (var i=0;i<geoXmlDoc.markers.length;i++) {
geoXmlDoc.markers[i].setVisible(false);
}
}
function unhide_markers_kml(){
for (var i=0;i<geoXmlDoc.markers.length;i++) {
geoXmlDoc.markers[i].setVisible(true);
}
}
function hide_polys_kml(){
for (var i=0;i<geoXmlDoc.gpolylines.length;i++) {
geoXmlDoc.gpolylines[i].setMap(null);
}
}
function unhide_polys_kml(){
for (var i=0;i<geoXmlDoc.gpolylines.length;i++) {
geoXmlDoc.gpolylines[i].setMap(map);
}
}
function load_kmlLayer() {
kmlLayer = new google.maps.KmlLayer(filename);
google.maps.event.addListener(kmlLayer, "status_changed", function() {
document.getElementById('kmlstatus').innerHTML = "Kml Status:"+kmlLayer.getStatus();
});
kmlLayer.setMap(map);
}
function hide_kmlLayer() {
kmlLayer.setMap(null);
}
function show_kmlLayer() {
kmlLayer.setMap(map);
}
</script>
</head>
<body onload="initialize()">
<h4>Reading a KML file with Google Maps JavaScript API Version 3 and geoxml3.</h4>
<!-- <button onclick="hide_polys_kml();">hide polylines</button>
<button onclick="unhide_polys_kml();">unhide polylines</button> -->
<button onclick="hide_kml();">hide</button>
<button onclick="unhide_kml();">unhide</button>
<button onclick="hide_markers_kml();">hide markers</button>
<button onclick="unhide_markers_kml();">show markers</button>
<button onclick="load_kmlLayer();">load kmlLayer</button>
<button onclick="hide_kmlLayer();">hide kmlLayer</button>
<button onclick="show_kmlLayer();">show kmlLayer</button>
<!-- <button onclick="reload_kml();">reload</button> -->
<table style="width:100%;"><tr><td>
<div id="map_canvas">
</div>
</td><td>
<div id="sidebar" style="width:300px;height:600px; overflow:auto"></div>
</td></tr>
<tr><td colspan="2"> <div id="link"></div></td></tr>
</table>
<div id="map_text">
</div>
<div id="kmlstatus"></div>
</body>
</html>
You need to set the "hotSpot" for your custom icons.
<hotSpot x="0.5" y="0.5" xunits="fraction" yunits="fraction">
Specifies the position within the Icon that is "anchored" to the specified in the Placemark. The x and y
values can be specified in three different ways: as pixels ("pixels"), as fractions of the icon ("fraction"), or as
inset pixels ("insetPixels"), which is an offset in pixels from the upper right corner of the icon. The x and y
positions can be specified in different ways—for example, x can be in pixels and y can be a fraction. The origin of > the coordinate system is in the lower left corner of the icon.
The hotSpot tag is (now) supported (correctly) in the kmz branch of geoxml3:
working example

how to reset value of steps in google maps v3 animation

this is my example http://gidzior.net/map/v3_animate_marker_directions.html (i'm using placeholder in the input), core of GM code is from geocodezip.com, i develop the code with the great help of Andrew Leach
1500 meters in the animation before the destination is set to zoom could be seen to better reach this destination point, unfortunately, after zoom, animation is not smooth and therefore I set the "step" value to 15, how to reset this value after animation stops
i set step = 15 - if (d>eol-1500 && zoomed!=true) { map.setZoom(15); step = 15; zoomed=true; }
WHOLE SCRIPT
var map;
var directionDisplay;
var directionsService;
var stepDisplay;
var markerArray = [];
var position;
var marker = null;
var polyline = null;
var poly2 = null;
var speed = 0.0000005, wait = 1;
var infowindow = null;
var zoomed;
var zoomedd;
var zoomeddd;
var myPano;
var panoClient;
var nextPanoId;
var timerHandle = null;
var size = new google.maps.Size(26,25);
var start_point = new google.maps.Point(0,0);
var foothold = new google.maps.Point(13,15);
var car_icon = new google.maps.MarkerImage("http://gidzior.net/map/car.png", size, start_point, foothold);
function createMarker(latlng, label, html) {
var contentString = '<b>'+label+'</b><br>'+html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: car_icon,
clickable: false,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
return marker;
}
function initialize() {
infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50)
});
// Instantiate a directions service.
directionsService = new google.maps.DirectionsService();
// Create a map and center it on Warszawa.
var myOptions = {
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
address = 'warszawa'
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
map.setCenter(results[0].geometry.location);
});
// Create a renderer for directions and bind it to the map.
var rendererOptions = {
map: map,
}
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
// Instantiate an info window to hold step text.
stepDisplay = new google.maps.InfoWindow();
polyline = new google.maps.Polyline({
path: [],
strokeColor: '#FF0000',
strokeWeight: 3
});
poly2 = new google.maps.Polyline({
path: [],
strokeColor: '#FF0000',
strokeWeight: 3
});
}
var steps = []
function calcRoute(){
if (timerHandle) { clearTimeout(timerHandle); }
if (marker) { marker.setMap(null);}
polyline.setMap(null);
poly2.setMap(null);
directionsDisplay.setMap(null);
polyline = new google.maps.Polyline({
path: [],
strokeColor: '#FF0000',
strokeWeight: 3
});
poly2 = new google.maps.Polyline({
path: [],
strokeColor: '#FF0000',
strokeWeight: 3
});
// Create a renderer for directions and bind it to the map.
var rendererOptions = {
map: map,
suppressMarkers:true
}
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var start = document.getElementById("start").value;
var end = document.getElementById("end").value;
var travelMode = google.maps.DirectionsTravelMode.DRIVING
var request = {
origin: start,
destination: end,
travelMode: travelMode,
waypoints: [{
location:new google.maps.LatLng(52.185570, 20.997255),
stopover:false}],
optimizeWaypoints: false
};
// Route the directions and pass the response to a
// function to create markers for each step.
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK){
directionsDisplay.setDirections(response);
var bounds = new google.maps.LatLngBounds();
var route = response.routes[0];
startLocation = new Object();
endLocation = new Object();
// For each route, display summary information.
var path = response.routes[0].overview_path;
var legs = response.routes[0].legs;
for (i=0;i<legs.length;i++) {
if (i == 0) {
startLocation.latlng = legs[i].start_location;
startLocation.address = legs[i].start_address;
// marker = google.maps.Marker({map:map,position: startLocation.latlng});
marker = createMarker(legs[i].start_location,"start",legs[i].start_address,"green");
}
endLocation.latlng = legs[i].end_location;
endLocation.address = legs[i].end_address;
var steps = legs[i].steps;
for (j=0;j<steps.length;j++) {
var nextSegment = steps[j].path;
for (k=0;k<nextSegment.length;k++) {
polyline.getPath().push(nextSegment[k]);
bounds.extend(nextSegment[k]);
}
}
}
polyline.setMap(map);
document.getElementById("distance").innerHTML = (polyline.Distance()/1000).toFixed(2)+" km";
map.fitBounds(bounds);
// createMarker(endLocation.latlng,"end",endLocation.address,"red");
map.setZoom(18);
startAnimation();
zoomed=false;
zoomedd=false;
zoomeddd=false;
}
});
}
var step = 50; // 5; // metres
var tick = 100; // milliseconds
var eol;
var k=0;
var stepnum=0;
var speed = "";
var lastVertex = 1;
//=============== animation functions ======================
function updatePoly(d) {
// Spawn a new polyline every 20 vertices, because updating a 100-vertex poly is too slow
if (poly2.getPath().getLength() > 20) {
poly2=new google.maps.Polyline([polyline.getPath().getAt(lastVertex-1)]);
// map.addOverlay(poly2)
}
if (polyline.GetIndexAtDistance(d) < lastVertex+2) {
if (poly2.getPath().getLength()>1) {
poly2.getPath().removeAt(poly2.getPath().getLength()-1)
}
poly2.getPath().insertAt(poly2.getPath().getLength(),polyline.GetPointAtDistance(d));
} else {
poly2.getPath().insertAt(poly2.getPath().getLength(),endLocation.latlng);
}
}
function animate(d) {
// alert("animate("+d+")");
if (d>eol) {;
map.panTo(endLocation.latlng);
marker.setPosition(endLocation.latlng);
return;
}
if (d>eol-20000 && zoomeddd!=true) {
map.setZoom(12); // or whatever value
zoomeddd=true;
}
if (d>eol-10000 && zoomedd!=true) {
map.setZoom(13); // or whatever value
zoomedd=true;
}
if (d>eol-1500 && zoomed!=true) {
map.setZoom(15); // or whatever value
step = 15;
zoomed=true;
}
var p = polyline.GetPointAtDistance(d);
map.panTo(p);
marker.setPosition(p);
updatePoly(d);
timerHandle = setTimeout("animate("+(d+step)+")", tick);
}
function startAnimation() {
eol=polyline.Distance();
map.setCenter(polyline.getPath().getAt(0));
// map.addOverlay(new google.maps.Marker(polyline.getAt(0),G_START_ICON));
// map.addOverlay(new GMarker(polyline.getVertex(polyline.getVertexCount()-1),G_END_ICON));
// map.addOverlay(marker);
poly2 = new google.maps.Polyline({path: [polyline.getPath().getAt(0)], strokeColor:"#0000FF", strokeWeight:10});
// map.addOverlay(poly2);
setTimeout("animate(50)",2000); // Allow time for the initial map display
}
I managed to get to this, thanks anyway
i took var step = 50; to the the top
var map;
var directionDisplay;
var directionsService;
var stepDisplay;
var markerArray = [];
var position;
var marker = null;
var polyline = null;
var poly2 = null;
var speed = 0.0000005, wait = 1;
var infowindow = null;
var zoomed;
var zoomedd;
var zoomeddd;
var step = 50; // 5; // metres
var myPano;
var panoClient;
var nextPanoId;
var timerHandle = null;
i set step = 50; to the end of calcRoute() function and now animation works fine

Javascript Google map api V3 fitbounds with center location

I want to fitbound pushpins to visible all around user's location pushpin. i wrote the following code it center the user location but few pushpin goes out of map ??
FYI: userPinLoc is pushpin object which is already populated
function setInitialZoom() {
mapZoom = googleMap.getZoom();
var bounds = new google.maps.LatLngBounds();
bounds.extend(userPinLoc);
for (i in nearestEntitiesToZoom) {
entity = nearestEntitiesToZoom[i];
var googleLatLng = new google.maps.LatLng(entity.latitude,entity.longitude);
bounds.extend(googleLatLng);
}
google.maps.event.addDomListener(googleMap, 'bounds_changed', function() {
googleMap.setCenter(userPinLoc);
});
googleMap.fitBounds(bounds);
}
I'm not sure where you're getting userPinLoc from. Give this a go:
...
var bounds = new google.maps.LatLngBounds();
// Go through each...
for (i in nearestEntitiesToZoom) {
entity = nearestEntitiesToZoom[i];
var googleLatLng = new google.maps.LatLng(entity.latitude, entity.longitude);
bounds.extend(googleLatLng);
};
// Fit these bounds to the map
googleMap.fitBounds(bounds);
...
Remember, fitCenter or fitBounds needs a LatLng object as a parameter.
This code is adapted from: http://you.arenot.me/2010/06/29/google-maps-api-v3-0-multiple-markers-multiple-infowindows/
I did it using java and javascript
public static void calculateMapFitBounds(GeoLocation userLocation, List<GeoLocation> contents, Map<String, GeoLocation> latlngBounds){
if (Util.isEmtpyGeoLocation(userLocation) || contents == null || contents.isEmpty()) {
return;
}
//SW
double minLat = userLocation.getLatitude();
double minLng = userLocation.getLongitude();
//NE
double maxLat = userLocation.getLatitude();
double maxLng = userLocation.getLongitude();
for(GeoLocation content: contents){
/*
* Populating Top left cordinate (SW)
*/
minLat = Math.min(minLat, content.getLatitude());
minLng = Math.min(minLng, content.getLongitude());
/*
* Populating Bottom right cordinate (NE)
*/
maxLng = Math.max(maxLng, content.getLongitude()) ;
maxLat = Math.max(maxLat, content.getLatitude());
}
/*
* Calculating Delta fit bounds
*/
double latDelta = Math.max(Math.abs(userLocation.getLatitude() - minLat), Math.abs(maxLat-userLocation.getLatitude()));
double lngDelta = Math.max(Math.abs(userLocation.getLongitude() - maxLng), Math.abs(minLng - userLocation.getLongitude()));
//Calculating SW
minLat = userLocation.getLatitude() - latDelta;
minLng = userLocation.getLongitude()- lngDelta;
latlngBounds.put("swLatLng", new GeoLocation(minLat, minLng));
//Calculating NE
maxLat = userLocation.getLatitude() + latDelta;
maxLng = userLocation.getLongitude()+ lngDelta;
latlngBounds.put("neLatLng", new GeoLocation(maxLat, maxLng));
}
I am using velocity views so here is velocity and js code
#if($swLatLng && $neLatLng)
var swLatLn = new google.maps.LatLng($!swLatLng.latitude, $!swLatLng.longitude, false);
var neLatLn = new google.maps.LatLng($neLatLng.latitude, $neLatLng.longitude, false);
var bounds = new google.maps.LatLngBounds(swLatLn, neLatLn);
googleMap.fitBounds(bounds);
#end
When I've done this before, I've done the bounds.extend() for the map center as the very last one, not the first one. Which seemed to work better for some reason.
function initialize() {
var points = [
{
lat: 51.498725,
lng: -0.17312
},
{
lat: 51.4754091676,
lng: -0.186810493469
},
{
lat: 51.4996066187,
lng: -0.113682746887
},
{
lat: 51.51531272,
lng: -0.176296234131
}
];
var centerLatLng = {lat: 51.532315, lng: -0.1544};
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 15,
center: centerLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var bounds = new google.maps.LatLngBounds();
var homeMarker = new google.maps.Marker({
position: centerLatLng,
map: map,
icon: "http://maps.google.com/mapfiles/ms/micons/green-dot.png"
});
for (var i = 0; i < points.length; i++) {
var marker = new google.maps.Marker({
position: points[i],
map: map
});
bounds.extend(points[i]);
}
bounds.extend(centerLatLng);
map.fitBounds(bounds);
}

Resources