fitBounds(bound) function not working properly - javascript

I have te following code:
var bound = new google.maps.LatLngBounds();
if (arrMarkers.length > 0) {
for (var i = 0; i < arrMarkers.length; i++) {
bound.extend(new google.maps.LatLng(arrMarkers[i].getPosition().lat(), arrMarkers[i].getPosition().lng()));
}
strDefaultLtLong = bound.getCenter();// get center from bounds
}
var image = 'Images/star.png';
var mapOptions = {
center: strDefaultLtLong,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDoubleClickZoom: true,
zoom: parseInt(strDefaultZoomLevel)
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
if (arrMarkers.length == 1) {
map.setZoom(parseInt(strDefaultZoomLevel));
}
else if (arrMarkers.length > 1) {
map.fitBounds(bound);
google.maps.event.addListener(map, 'idle', function (event) {
if (map.getZoom() > parseInt(strDefaultZoomLevel)) {
map.setZoom(parseInt(strDefaultZoomLevel));
}
});
google.maps.event.clearListeners(map, 'idle');
}
I have list of locations in arrMarkers. fitBounds() function works only if locations have different location but if list of locations has same location(Lat&Long) then it displays fully zoomed map.
How can I handle that to default zoom or particular zoom level so that listing will display appropriatly?
Thanks..

if the locations of the markers are really equal, you may compare the SW and the NE of the bounds, they should be equal too:
//if (arrMarkers.length == 1) {
if(bounds.getSouthWest().toUrlValue()
===
bounds.getNorthEast().toUrlValue()){
map.setZoom(parseInt(strDefaultZoomLevel));
}
Demo:
function init() {
var goo=google.maps,
strDefaultZoomLevel='7',
map = new goo.Map(document.getElementById('map_canvas'),
{
zoom: parseInt(strDefaultZoomLevel),
noClear:true
}),
btn=document.getElementById('btn'),
markers=[
new goo.Marker({position:{lat:11.11,lng:22.22},
icon:{
url:'http://maps.google.com/mapfiles/dir_0.png',
scaledSize:new goo.Size(48,48)
}}),
new goo.Marker({position:{lat:11.11,lng:22.22},
icon:{
url:'http://maps.google.com/mapfiles/dir_60.png',
scaledSize:new goo.Size(48,48)
}}),
new goo.Marker({position:{lat:66.66,lng:77.77},
icon:{
url:'http://maps.google.com/mapfiles/dir_0.png',
scaledSize:new goo.Size(48,48)
}})
];
map.controls[goo.ControlPosition.BOTTOM_CENTER]
.push(btn);
goo.event.addDomListener(btn,'click',function(){
for(var i=0;i<markers.length;++i){
markers[i].setMap(null);
}
this.value=(this.value==='draw equal markers')
? 'draw different markers'
: 'draw equal markers';
var arrMarkers=markers.slice.apply(markers,(this.value==='draw equal markers')
? [1,3]
: [0,2]),
bounds=new goo.LatLngBounds();
for(var i=0;i<arrMarkers.length;++i){
arrMarkers[i].setMap(map);
bounds.extend(arrMarkers[i].getPosition());
}
if(bounds.getSouthWest().toUrlValue()
===
bounds.getNorthEast().toUrlValue()){
map.setOptions({
zoom:parseInt(strDefaultZoomLevel),
center:bounds.getCenter()
});
}
else{
map.fitBounds(bounds);
}
});
google.maps.event.trigger(btn,'click');
}
html,body,#map_canvas{height:100%;margin:0;padding:0;}
#btn{font:14px bold Monospace;background:tomato;margin-bottom:12px;}
<div id="map_canvas">
<input id="btn" type="button" value="draw equal markers"/>
</div>
<script src="https://maps.googleapis.com/maps/api/js?v=3&callback=init"></script>

Related

Google Map Direction Render Alternate Route How To Select Desired Path

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>

Speed up Google Map

I have a asp.net 4.0 page that loads a Google map, with over 6,000 markers (and growing!)
I am loading the markers from my SQL DB, using a repeater control in the javascript like in this [this example:] (http://www.aspsnippets.com/Articles/ASPNet-Populate-Google-Maps-V3-with-Multiple-Markers-using-Address-Latitude-and-Longitude-values-stored-in-database.aspx)
I have already added marker clustering and done everything I can think of to speed it up.
Some of the markers are added during the initial load, but are not displayed on the map until the user zooms in. (via height:1 width:1 for the cluster icon)
Here is what I want to do, but I'm not sure if it is possible. I want to have my vb codebehind/asp:Repeater load the markers that will display initially. Then in the "Idle" listner, have it load the other markers so that they are ready once the map is zoomed in.
BUT, I can't figure out how to accomplish this. Any ideas?
Here is the bulk of the javascript:
// configure options
var map;
var locations = new Array();
var markers = new Array();
var markerCluster1 = null;
var markerCluster2 = null;
var markerCluster3 = null;
var markerCluster4 = null;
var Style1 = [{url: '../images/m1.png',
height: 48,
width: 48
}];
var Style2 = [{url: '../images/m2.png',
height: 48,
width: 48
}];
var Style3 = [{url: '../images/m3.png',
height: 48,
width: 48
}];
var Style4 = [{url: '../images/m4.png',
textSize: 1,
height: 1,
width: 1
}];
var mcOA1 = {gridSize: 50, maxZoom: 10, styles: Style1};
var mcOA2 = {gridSize: 50, maxZoom: 10, styles: Style2};
var mcOA3 = {gridSize: 50, maxZoom: 10, styles: Style3};
var mcOA4 = {gridSize: 300, maxZoom: 9, styles: Style4, minimumClusterSize: 2};
var infoWindow = new google.maps.InfoWindow();
<asp:Repeater ID="rptMarkers" runat="server" EnableViewState = false>
<ItemTemplate>locations[<%# Eval("i")%>]=new Array(),locations[<%# Eval("i")%>][0]='<%# Eval("PType")%>',locations[<%# Eval("i")%>][1]='<%# Eval("Lat")%>',locations[<%# Eval("i")%>][2]='<%# Eval("Lon")%>',locations[<%# Eval("i")%>][3]='<div class=\"info-window\"><%# Eval("MDesc")%></div>',locations[<%# Eval("i")%>][4]='<%# Eval("Name") %>';
</ItemTemplate>
<SeparatorTemplate></SeparatorTemplate>
</asp:Repeater>
function initialize() {
var myOptions =
<asp:Repeater ID="MapOptions" runat="server">
<ItemTemplate>
{
center: new google.maps.LatLng(<%# Eval("center")%>),
zoom: <%# Eval("zoom")%>,
streetViewControl: false,
mapTypeId: <%# Eval("mapTypeId")%>
}
</ItemTemplate>
</asp:Repeater>
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
for (i = 1; i < locations.length; i++) {
if (typeof(locations[i]) == 'object') {
var icon = "";
switch (locations[i][0]) {
case "A1":
icon = "../images/A13.png";
break;
case "A2":
icon = "../images/A23.png";
break;
case "A3":
icon = "../images/A33.png";
break;
case "A4":
icon="../images/A44.png"
break;
case "Furniture":
icon="../images/Furniture3.png"
break;
case "Property Manager":
icon="../images/PropertyManager3.png"
break;
default:
icon="../images/A13.png"
break;
}
var point = new google.maps.LatLng(locations[i][1], locations[i][2]);
markers[i] = new google.maps.Marker({
position: point,
icon: new google.maps.MarkerImage(icon),
animation: google.maps.Animation.DROP,
title: locations[i][4]
});
markers[i].setMap(map);
google.maps.event.addListener(markers[i], 'click', function() {infoWindow.setContent(locations[i][3]);infoWindow.open(map, markers[i]);});
}
} // for
// check to see which category is selected
var location_selector = document.getElementsByName('loc_sel');
for (var i=0; i < location_selector.length; i++) {
if (location_selector[i].checked) {
var location_type = location_selector[i].value;
}
}
show_markers(location_type);
} // function initialize() {
function show_markers (location_type) {
var temp_markers1 = new Array();
var temp_markers2 = new Array();
var temp_markers3 = new Array();
var temp_markers4 = new Array();
// if the markerClusterer object doesn't exist, create it with empty temp_markers
if (markerCluster1 == null) {
markerCluster1 = new MarkerClusterer(map, temp_markers1, mcOA1);
}
if (markerCluster2 == null) {
markerCluster2 = new MarkerClusterer(map, temp_markers1, mcOA2);
}
if (markerCluster3 == null) {
markerCluster3 = new MarkerClusterer(map, temp_markers1, mcOA3);
}
if (markerCluster4 == null) {
markerCluster4 = new MarkerClusterer(map, temp_markers1, mcOA4);
}
// clear all markers
markerCluster1.clearMarkers();
markerCluster2.clearMarkers();
markerCluster3.clearMarkers();
markerCluster4.clearMarkers();
// iterate through all locations, setting only those in the selected category
for (i = 1; i < locations.length; i++) {
if (typeof(locations[i]) == 'object') {
if (locations[i][0] == location_type) {
markers[i].setVisible(true);
if (locations[i][0] == "A1") {temp_markers1.push(markers[i]);}
if (locations[i][0] == "A2") {temp_markers2.push(markers[i]);}
if (locations[i][0] == "A3") {temp_markers3.push(markers[i]);}
if (locations[i][0] == "A4") {temp_markers4.push(markers[i]);}
} else {
markers[i].setVisible(false);
if (locations[i][0] == "A4") {markers[i].setVisible(true);
temp_markers4.push(markers[i]);}
}
}
} // for
// add all current markers to cluster
markerCluster1.addMarkers(temp_markers1);
markerCluster2.addMarkers(temp_markers2);
markerCluster3.addMarkers(temp_markers3);
markerCluster4.addMarkers(temp_markers4);
} // function show_markers
Thank you all!
One probable solution to this problem may be to fire a query to the SQL DB to fetch all the markers when the map is in the idle state.
google.maps.event.addListener(map, 'idle', function() {
fetchMarkersfromDB();
});
And in the initialize() function pass both this listener and also the showMarker() function call. So that whenever the maps are initialized and displayed the markers at current zoom position would be displaced and during the idle phase the query in the backgroud would fetch remaining markers that can be shown in the next or consequent zoom levels. This way the markers would be ready and performance will be better.
Hope this would help!!

Markers image are not displaying, only the last one because of css

I have a google map which was working well until a few weeks ago.
My problem is that now, all the label markers appears in the right place but only the last image appears.
I see in the generated html code that all images are here but all of them have the same position (that's why i can just see the last one).
I say again : it was working before, i'm sure! Maybe google has changed something (i'm calling the script : https://maps.googleapis.com/maps/api/js?sensor=false).
Here is my code :
jQuery(function() {
var stops = [];
var nbPoints = $('#nbPoints').val();
for (var i = 1; i <= nbPoints; i++) {
if($('#latitude'+i).val() && $('#longitude'+i).val())
stops.push({"Geometry":{"Latitude":$('#latitude'+i).val(),"Longitude":$('#longitude'+i).val()}});
}
var map = new window.google.maps.Map(document.getElementById("map_canvas"));
// new up complex objects before passing them around
var directionsDisplay = new window.google.maps.DirectionsRenderer({suppressMarkers: true});
var directionsService = new window.google.maps.DirectionsService();
Tour_startUp(stops);
window.tour.loadMap(map, directionsDisplay);
window.tour.fitBounds(map);
if (stops.length > 1)
window.tour.calcRoute(directionsService, directionsDisplay);
else $("#message").html("Erreur : Aucune coordonnée renseignée!");
});
function Tour_startUp(stops) {
if (!window.tour) window.tour = {
updateStops: function (newStops) {
stops = newStops;
},
// map: google map object
// directionsDisplay: google directionsDisplay object (comes in empty)
loadMap: function (map, directionsDisplay) {
var myOptions = {
zoom: 13,
center: new window.google.maps.LatLng($('#latitudeInit').val(),$('#longitudeInit').val()),
mapTypeId: window.google.maps.MapTypeId.ROADMAP
};
map.setOptions(myOptions);
directionsDisplay.setMap(map);
},
fitBounds: function (map) {
var bounds = new window.google.maps.LatLngBounds();
// extend bounds for each record
jQuery.each(stops, function (key, val) {
var myLatlng = new window.google.maps.LatLng(val.Geometry.Latitude, val.Geometry.Longitude);
bounds.extend(myLatlng);
});
map.fitBounds(bounds);
},
calcRoute: function (directionsService, directionsDisplay) {
var batches = [];
var itemsPerBatch = 10; // google API max = 10 - 1 start, 1 stop, and 8 waypoints
var itemsCounter = 0;
var wayptsExist = stops.length > 0;
while (wayptsExist) {
var subBatch = [];
var subitemsCounter = 0;
for (var j = itemsCounter; j < stops.length; j++) {
subitemsCounter++;
subBatch.push({
location: new window.google.maps.LatLng(stops[j].Geometry.Latitude, stops[j].Geometry.Longitude),
stopover: true
});
if (subitemsCounter == itemsPerBatch)
break;
}
itemsCounter += subitemsCounter;
batches.push(subBatch);
wayptsExist = itemsCounter < stops.length;
// If it runs again there are still points. Minus 1 before continuing to
// start up with end of previous tour leg
itemsCounter--;
}
// now we should have a 2 dimensional array with a list of a list of waypoints
var combinedResults;
var unsortedResults = [{}]; // to hold the counter and the results themselves as they come back, to later sort
//var directionsResultsReturned = 0;
var directionsResultsReturned = new Array();
directionsResultsReturned[0]=0;
for (var k = 0; k < batches.length; k++) {
var lastIndex = batches[k].length - 1;
var start = batches[k][0].location;
var end = batches[k][lastIndex].location;
// trim first and last entry from array
var waypts = [];
waypts = batches[k];
waypts.splice(0, 1);
waypts.splice(waypts.length - 1, 1);
var request = {
origin: start,
destination: end,
waypoints: waypts,
travelMode: window.google.maps.TravelMode.DRIVING
};
creerRoute(k,request,batches,directionsService,unsortedResults,combinedResults,directionsResultsReturned,directionsDisplay);
}
}
};
}
var infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50)
});
var icons = new Array();
icons["red"] = new google.maps.MarkerImage("mapIcons/marker_red.png",
// This marker is 20 pixels wide by 34 pixels tall.
new google.maps.Size(20, 34),
// The origin for this image is 0,0.
new google.maps.Point(0,0),
// The anchor for this image is at 9,34.
new google.maps.Point(9, 34));
function getMarkerImage(numero, type, anomalie) {
var url_img = "../img/";
var type = new String(type);
if(anomalie) url_img+="anomalie.png";
else{
switch(type.toUpperCase()){
case "LAVAGE" : url_img+="shower.png"; break;
case "EAU" : url_img+="waterdrop.png"; break;
default : url_img+="stop.png"; break;
}
}
icons[numero] = new google.maps.MarkerImage(url_img,
new google.maps.Size(34, 34),
new google.maps.Point(0,0),
new google.maps.Point(9, 34));
return icons[numero];
}
// Marker sizes are expressed as a Size of X,Y
// where the origin of the image (0,0) is located
// in the top left of the image.
// Origins, anchor positions and coordinates of the marker
// increase in the X direction to the right and in
// the Y direction down.
var iconImage = new google.maps.MarkerImage('mapIcons/marker_red.png',
// This marker is 20 pixels wide by 34 pixels tall.
new google.maps.Size(34, 34),
// The origin for this image is 0,0.
new google.maps.Point(0,0),
// The anchor for this image is at 9,34.
new google.maps.Point(9, 34));
var iconShadow = new google.maps.MarkerImage('http://www.google.com/mapfiles/shadow50.png',
// The shadow image is larger in the horizontal dimension
// while the position and offset are the same as for the main image.
new google.maps.Size(37, 34),
new google.maps.Point(0,0),
new google.maps.Point(9, 34));
// Shapes define the clickable region of the icon.
// The type defines an HTML <area> element 'poly' which
// traces out a polygon as a series of X,Y points. The final
// coordinate closes the poly by connecting to the first
// coordinate.
var iconShape = {
coord: [9,0,6,1,4,2,2,4,0,8,0,12,1,14,2,16,5,19,7,23,8,26,9,30,9,34,11,34,11,30,12,26,13,24,14,21,16,18,18,16,20,12,20,8,18,4,16,2,15,1,13,0],
type: 'poly'
};
function createMarker(map, latlng, label, html, numero, type, anomalie) {
var contentString = '<b>'+label+'</b><br>'+html;
var marker = new MarkerWithLabel({
position: latlng,
map: map,
draggable: false,
raiseOnDrag: true,
icon : getMarkerImage(numero,type,anomalie),
labelContent: numero,
labelAnchor: new google.maps.Point(0, 0),
labelClass: "labels",
labelInBackground: false
});
marker.myname = label;
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
return marker;
}
function creerRoute(kk,request,batches,directionsService,unsortedResults,combinedResults,directionsResultsReturned,directionsDisplay) {
directionsService.route(request, function (result, status) {
if (status == window.google.maps.DirectionsStatus.OK) {
var unsortedResult = { order: kk, result: result };
unsortedResults.push(unsortedResult);
directionsResultsReturned[0]++;
if (directionsResultsReturned[0] == batches.length) // we've received all the results. put to map
{
// sort the returned values into their correct order
unsortedResults.sort(function (a, b) { return parseFloat(a.order) - parseFloat(b.order); });
var count = 0;
for (var key in unsortedResults) {
if (unsortedResults[key].result != null) {
if (unsortedResults.hasOwnProperty(key)) {
if (count == 0) // first results. new up the combinedResults object
combinedResults = unsortedResults[key].result;
else {
// only building up legs, overview_path, and bounds in my consolidated object. This is not a complete
// directionResults object, but enough to draw a path on the map, which is all I need
combinedResults.routes[0].legs = combinedResults.routes[0].legs.concat(unsortedResults[key].result.routes[0].legs);
combinedResults.routes[0].overview_path = combinedResults.routes[0].overview_path.concat(unsortedResults[key].result.routes[0].overview_path);
combinedResults.routes[0].bounds = combinedResults.routes[0].bounds.extend(unsortedResults[key].result.routes[0].bounds.getNorthEast());
combinedResults.routes[0].bounds = combinedResults.routes[0].bounds.extend(unsortedResults[key].result.routes[0].bounds.getSouthWest());
}
count++;
}
}
}
directionsDisplay.setDirections(combinedResults);
var legs = combinedResults.routes[0].legs;
for (var i=0; i < legs.length;i++){
var j = i + 1;
var markerletter = $('#ordre'+j).val();
var anomalie=false;
var html = $('#infospoint'+j).val();
if($('#infoschocspoint'+j).length){
anomalie = true;
html+="<br/>"+$('#infoschocspoint'+j).val();
}
createMarker(directionsDisplay.getMap(),legs[i].start_location,$('#titrepoint'+j).val(),html,markerletter,$('#type'+j).val(),anomalie);
}
var i=legs.length + 1;
var markerletter = $('#ordre'+i).val();
var anomalie=false;
var html = $('#infospoint'+i).val();
if($('#infoschocspoint'+i).length){
anomalie = true;
html+="<br/>"+$('#infoschocspoint'+i).val();
}
createMarker(directionsDisplay.getMap(),legs[legs.length-1].end_location,$('#titrepoint'+i).val(),html,markerletter,$('#type'+i).val(),anomalie);
}
}else {
if (status == window.google.maps.DirectionsStatus.OVER_QUERY_LIMIT) {
setTimeout( function(){
creerRoute(kk,request,batches,directionsService,unsortedResults,combinedResults,directionsResultsReturned,directionsDisplay);
}, 200);
}else{
$("#message").html("Erreur : Code "+status);
}
}
});
}
Has anyone the same problem?
Thanks for your help!
You can use new one
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&v=3.3"></script>

IE Issue of Google Maps Marker Animation

I am using google maps api v3.
The Below code i am trying to run , It is working on all Browsers except IE.
Can u please suggest any changes needed to work in IE.
Fiddle Link
My Code is :
var map;
var mapOptions = { center: new google.maps.LatLng(0.0, 0.0), zoom: 2,
mapTypeId: google.maps.MapTypeId.ROADMAP };
var markers = [];
function initialize() {
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
from1 = new google.maps.LatLng(0,0);
to1 = new google.maps.LatLng(30,12);
from2 = new google.maps.LatLng(-30,15);
to2 = new google.maps.LatLng(10,-100);
from3 = new google.maps.LatLng(0,-50);
to3 = new google.maps.LatLng(0,50);
addMarker(from1,to1);
addMarker(from2,to2);
addMarker(from3,to3);
}
function addMarker(pos, dest) {
var marker = new google.maps.Marker({
map: map,
position: pos,
destination: dest
});
google.maps.event.addListener(marker, 'click', function(event) {
fromLat = this.position.lat();
fromLng = this.position.lng();
toLat = this.destination.lat();
toLng = this.destination.lng();
// store a LatLng for each step of the animation
frames = [];
for (var percent = 0; percent < 1; percent += 0.01) {
curLat = fromLat + percent * (toLat - fromLat);
curLng = fromLng + percent * (toLng - fromLng);
frames.push(new google.maps.LatLng(curLat, curLng));
}
move = function(marker, latlngs, index, wait, newDestination) {
marker.setPosition(latlngs[index]);
if(index != latlngs.length-1) {
// call the next "frame" of the animation
setTimeout(function() {
move(marker, latlngs, index+1, wait, newDestination);
}, wait);
}
else {
// assign new route
marker.position = marker.destination;
marker.destination = newDestination;
}
}
// begin animation, send back to origin after completion
move(marker, frames, 0, 20, marker.position);
});
markers.push(marker);
}
google.maps.event.addDomListener(window, 'load', initialize);
After some fiddling it looks like a typing issue. Because you haven't implicitly declared the variable frames as a var ie is unsure that it is an array, thus the error "Object does not support method push".
You simply need to change:
frames = [];
to:
var frames = [];
Tested in ie 8- 10.

Marker clusterer country level

Is there a way to cluster markers at a country level? I am satisfied with the way the clustering currently works but would like to seperate it at a country level on initial load then normal cluster (or what ever is easier) as the user zooms in. I am currently testing this with some google example code
var markerClusterer = null;
var map = null;
var imageUrl = 'http://chart.apis.google.com/chart?cht=mm&chs=24x32&' +
'chco=FFFFFF,008CFF,000000&ext=.png';
google.maps.event.addDomListener(window, 'load', initialize);
function refreshMap() {
if (markerClusterer) {
markerClusterer.clearMarkers();
}
var markers = [];
var markerImage = new google.maps.MarkerImage(imageUrl,
new google.maps.Size(24, 32));
for (var i = 0; i < 1000; ++i) {
var latLng = new google.maps.LatLng(data.photos[i].latitude,
data.photos[i].longitude)
var marker = new google.maps.Marker({
position: latLng,
draggable: true,
icon: markerImage
});
markers.push(marker);
}
var zoom = parseInt(document.getElementById('zoom').value, 10);
var size = parseInt(document.getElementById('size').value, 10);
var style = parseInt(document.getElementById('style').value, 10);
zoom = zoom == -1 ? null : zoom;
size = size == -1 ? null : size;
style = style == -1 ? null: style;
markerClusterer = new MarkerClusterer(map, markers, {
maxZoom: zoom,
gridSize: size,
styles: styles[style]
});
}
function initialize() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 2,
center: new google.maps.LatLng(39.91, 116.38),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var refresh = document.getElementById('refresh');
google.maps.event.addDomListener(refresh, 'click', refreshMap);
var clear = document.getElementById('clear');
google.maps.event.addDomListener(clear, 'click', clearClusters);
refreshMap();
}
function clearClusters(e) {
e.preventDefault();
e.stopPropagation();
markerClusterer.clearMarkers();
}
The current code clusters to a default grid size that can be defined by the developer. I wish to implement a polygon type clustering though, not a grid size. If anybody knows how to do this please help.
EDITED
I've been trying for at least an hour and a half to get the suggested solution to work, here is my code
function initialize() {
var center = new google.maps.LatLng(46.468133,1.494141);
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var markers = [];
for (var i = 0; i < 7; i++) {
var dataPhoto = data.photos[i];
var latLng = new google.maps.LatLng(dataPhoto.latitude,
dataPhoto.longitude);
var marker = new google.maps.Marker({
position: latLng
});
marker.country = dataPhoto.country;
markers.push(marker);
}
var markerCluster = new MarkerClusterer(map, markers, {
countryZoom: 3,
});
this.countryZoom = options['countryZoom'] ;
}
google.maps.event.addDomListener(window, 'load', initialize);
Data
var data = {"count": 10785236,
"photos": [
{
"photo_id": 27932,
"latitude" : 43.516689,
"longitude" : -0.703125,
"country": "France"
}, {
"photo_id": 27342,
"latitude": 43.802819,
"longitude": 4.262695,
"country": "France"
}, {
"photo_id": 24932,
"latitude": 48.312428,
"longitude": -3.55957,
"country": "France"
}, {
"photo_id": 23332,
"latitude": 50.597186,
"longitude": 2.219238,
"country": "France"
}, {
"photo_id": 57932,
"latitude": 48.777913,
"longitude": 7.426758,
"country": "France"
}, {
"photo_id": 65432,
"latitude": 48.980217,
"longitude": 8.964844,
"country": "Germany"
}, {
"photo_id": 65432,
"latitude": 47.813155,
"longitude": 7.382813,
"country": "France"
}
]
}
Plugin edits
// Get our current map view bounds.
// Create a new bounds object so we don't affect the map.
var mapBounds = new google.maps.LatLngBounds(this.map_.getBounds().getSouthWest(),
this.map_.getBounds().getNorthEast());
var bounds = this.getExtendedBounds(mapBounds);
for (var i = 0, marker; marker = this.markers_[i]; i++) {
var added = false;
if (!marker.isAdded && this.isMarkerInBounds_(marker, bounds)) {
// this.addToClosestCluster_(marker);
for (var j = 0, cluster; cluster = this.clusters_[j]; j++) {
// *** Check if the current zoom level is for clustering
// based on countries
if (this.countryZoom && this.countryZoom == this.map_.getZoom()) {
if (!added && cluster.country == marker.country) {
added = true;
cluster.addMarker(marker);
break;
}
} else {
if (!added && cluster.getCenter() && cluster.isMarkerInClusterBounds(marker)) {
added = true;
cluster.addMarker(marker);
break;
}
}
}
if (!added) {
// Create a new cluster.
var cluster = new Cluster(this);
// *** Check if the current zoom level is for clustering
// based on countries
if (this.countryZoom && this.countryZoom == this.map_.getZoom()) {
cluster.country = marker.country;
}
cluster.addMarker(marker);
this.clusters_.push(cluster);
}
}
}
};
It still does not batch to country though

Categories

Resources