Add animated PNG. to polyline in google maps API - google-maps-api-3

I'm trying to animate a icon over a polyline like in this example: https://developers-dot-devsite-v2-prod.appspot.com/maps/documentation/javascript/examples/overlay-symbol-animate.
It works but I want to add my own PNG as the icon that is being animated. This is what I tried:
var line = new google.maps.Polyline({
path: [{ lat: 25.774266, lng: -80.193659 }, { lat: 25.83333, lng: 25.83333 - 77.8999964 }],
icons: [{
icon: CruiseShip //This is my .PNG file
}],
strokeColor: '#ffffff',
strokeWeight: 1,
map: map
});
function animateCircle(line) {
var count = 0;
window.setInterval(function () {
count = (count + 1) % 200;
var icons = line.get('icons');
icons[0].offset = (count / 2) + '%';
line.set('icons', icons);
}, 20);
}
Using the lineSymbol object like in the example does work. How can I add a .PNG file to the polyline instead of the lineSymbol? Couldn't find any documentation on this.

The way you are trying to animate the icon only works for SVG Symbols.
Mike Williams wrote an extension to the Google Maps Javascript API v2 (now deprecated and turned off) called epoly which contains the method .GetPointAtDistance, which can be used to update the position of a "normal" icon along a polyline.
There is a interpolate method in the google.maps.geometry.spherical library which interpolates between two points, but isn't very accurate for large scale features.
proof of concept fiddle
code snippet:
// This example creates a 2-pixel-wide red polyline showing the path of
// the first trans-Pacific flight between Oakland, CA, and Brisbane,
// Australia which was made by Charles Kingsford Smith.
function initMap() {
updatePolylinePrototype();
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {
lat: 0,
lng: -180
},
mapTypeId: 'terrain'
});
var line = new google.maps.Polyline({
path: [{
lat: 25.774266,
lng: -80.193659
}, {
lat: 25.83333,
lng: 25.83333 - 77.8999964
}, {
lat: 28.411413,
lng: -16.5449611
}],
strokeColor: '#ffffff',
strokeWeight: 1,
map: map
});
var marker = new google.maps.Marker({
icon: {
url: "http://earth.google.com/images/kml-icons/track-directional/track-12.png",
anchor: new google.maps.Point(12, 12),
scaledSize: new google.maps.Size(24, 24),
},
position: line.getPath().getAt(0),
map: map
})
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < line.getPath().getLength(); i++) {
bounds.extend(line.getPath().getAt(i));
}
map.fitBounds(bounds);
animateShip(line, marker);
}
function animateShip(line, marker) {
var count = 0;
var lineDistance = 0;
for (var i = 1; i < line.getPath().getLength(); i++) {
lineDistance += google.maps.geometry.spherical.computeDistanceBetween(line.getPath().getAt(i - 1), line.getPath().getAt(i))
}
window.setInterval(function() {
count = (count + 1) % 200;
marker.setPosition(line.GetPointAtDistance(lineDistance - (lineDistance * count / 200)));
}, 20);
}
function updatePolylinePrototype() {
// === A method which returns a GLatLng of a point a given distance along the path ===
// === Returns null if the path is shorter than the specified distance ===
google.maps.Polyline.prototype.GetPointAtDistance = function(metres) {
// some awkward special cases
if (metres == 0) return this.getPath().getAt(0);
if (metres < 0) return null;
if (this.getPath().getLength() < 2) return null;
var dist = 0;
var olddist = 0;
for (var i = 1;
(i < this.getPath().getLength() && dist < metres); i++) {
olddist = dist;
dist += google.maps.geometry.spherical.computeDistanceBetween(this.getPath().getAt(i), this.getPath().getAt(i - 1));
}
if (dist < metres) {
return null;
}
var p1 = this.getPath().getAt(i - 2);
var p2 = this.getPath().getAt(i - 1);
var m = (metres - olddist) / (dist - olddist);
return new google.maps.LatLng(p1.lat() + (p2.lat() - p1.lat()) * m, p1.lng() + (p2.lng() - p1.lng()) * m);
}
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=geometry">
</script>

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>

raphael.js css for pulsing dots does not work as I expected

I have created the following code based on the tutorial :http://webdesignerwall.com/tutorials/interactive-world-javascript-map.
This is the link to the source code of html file https://gist.github.com/anonymous/84795387d09fe08ee8b6
I have alterate it to display radomly one dot at the time on the map. But what I want to do is to have the dots displayed with a "pulse" effect. Originally the dots are displayed in the correct location, but when I added the following to class to activate the pulse effect the location of the circles changed...I've tried to change the scale but still does not work.. when I removed the scale then it stopped "pulsing". Do you have any ideas on the matter?
$( document ).ready(function() {
//Load the map after the page loads
if (window.addEventListener){ // W3C standard
window.addEventListener('load', function(){worldmap()}, false); //true means that this request will be ignored if auto is set to off
}
else if (window.attachEvent){ // Microsoft
window.attachEvent('onload', function(){worldmap()});
}
function worldmap(){
image_array=[];
var div = document.getElementById('map');
var width=div.offsetWidth;
var scale=width/887;
var height=width*.62;
var paper = Raphael(div, width, height); //create the Raphael canvas in the map div
var background=paper.rect(0, 0, width, height); //create the background
background.attr({fill: ' rgba(32, 32, 32, 1)', 'stroke-width': 0});
//create the map
var map_path="m 267.53333,537.24584 c -0.6,-0.6 -1,...couldn't put the whole path due to charecter limitation";
var map=paper.path(map_path).attr({fill: '#483D8B', stroke: 'white'}).scale(scale, scale, 0, 0);
//create set of locations
var location_set=paper.set();
//create locations
for (var location in locations){
var loc=locations[location];
var xy=get_xy(loc.lat, loc.lng);
var loc_obj=paper.circle(xy.x, xy.y, 7).attr({fill: loc.color, stroke: 'white', 'stroke-width': 2, }).scale(scale, scale, 0, 0);
loc_obj.node.setAttribute("id","i"+location)
loc_obj.node.setAttribute("class","loader")
loc_obj.hide();
loc_obj.name=loc.name;
loc_obj.x=xy.x;
loc_obj.y=xy.y;
location_set.push(loc_obj);
}
var name = document.getElementById('location_name');
// *********************************************Functions *********************************************
function get_xy(lat, lng){ //http://stackoverflow.com/questions/14329691/covert-latitude-longitude-point-to-a-pixels-x-y-on-mercator-projection
var mapWidth=2058;
var mapHeight=1746;
var factor=.404;
var x_adj=-391;
var y_adj=37;
// get x value
var x = (mapWidth*(180+lng)/360)%mapWidth+(mapWidth/2);
//convert from degrees to radians
var latRad = lat*Math.PI/180;
// get y value
var mercN = Math.log(Math.tan((Math.PI/4)+(latRad/2)));
var y = (mapHeight/2)-(mapWidth*mercN/(2*Math.PI));
return { x: x*factor+x_adj, y: y*factor+y_adj}
}
function GetLocationsLength(location){
function ObjectLength( location ) {
var length = 0;
for( var key in location ) {
if( location.hasOwnProperty(key) ) {
++length;
}
}
return length;
};
l=ObjectLength( location );
RandomGenerator(l,locations,location_set);
} //end of selfinvoked Random_Generator
GetLocationsLength(locations)
function RandomGenerator(length,locations,location_set){
location_set[0].show(); //console.log(innerHtml);
var counter=0;
var x=0;
previousX=-1;
var refreshId = setInterval( function() {
x = Math.floor((Math.random() * location_set.length) ); //generates a random number between 0-4
if(counter==0)
{location_set[0].show();
previousX=0;
}
counter++;
location_set[previousX].hide();
location_set[x].show();
//add elements to the box
// var flag = locations[x].name.toString();
//$("img#location").attr("src", flag);
$("img#location").css({"width": "40px", "height": "20px"});
$("span#name").text( locations[x].name).show('slow');
var link = locations[x].name.toString();
$("a#instituteLink").attr("href", link);
$("span#instituteLink").text( locations[x].name).show('slow');
previousX=x;
}, 6000); //end of refreshid funvtion
}//end of function RandomGenerator
}// end of world map function
// *********************************************Location Data*********************************************
var locations={
0: {
name: 'Paris',
lat: 48.866666670,
lng: 2.333333333,
color: 'violet',
},
1: {
name: 'Shanghai',
lat: 31.10,
lng: 121.366,
color: 'black',
},
2: {
name: 'New York',
lat: 40.7,
lng: -73.90,
color: 'red',
},
3: {
name: 'Los Angeles',
lat: 34.0,
lng: -118.25,
color: 'purple',
},
4: {
name: 'Cape Town',
lat: -35.916,
lng: 18.36,
color: 'hotpink',
},
5: {
name: 'Santiago',
lat: -33.45,
lng: -70.66,
color: 'blue',
},
6: {
name: 'Cairo',
lat: 30.05,
lng: 31.25,
color: 'green',
},
7: {
name: 'yolo',
lat: 40.05,
lng: 11.25,
color: 'green',
},
8: {
name: 'Singapore',
lat: 1.30,
lng: 103.83,
color: 'orange',
}
}
});

google map viewport auto adjust

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

Google Maps marker and polyline color not rendered in IE7/8

I have a Google Maps v3 on my site that displays markers and polylines. Each set of markers + polylines have their own colors (red, yellow, blue, etc.). This works fine in FF/Chrome/Safari but not in IE7/8 (Work fine in IE9).
Here is what the markers look like in IE8/XP:
The markers should look like this (in Chrome):
There are no js errors in DevTool or Firebug Lite.
Here is the code I'm using to display the markers and polylines:
Maps = {
googleMap: null,
paths: [],
wayPoints: null,
colors: ["#00aeef", "#ec008c", "#41ad49", "#d2232a", "#fff200"],
minZoomLevel: 2,
init: function () {
var mapOptions = {
zoom: Maps.minZoomLevel,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
Maps.googleMap = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
google.maps.event.addListener(Maps.googleMap, 'zoom_changed', function() {
if (Maps.googleMap.getZoom() < Maps.minZoomLevel)
Maps.googleMap.setZoom(Maps.minZoomLevel);
});
},
plotPaths: function (paths) {
if (paths && paths.length === 0) {
var latLng = new google.maps.LatLng(41.850033,-87.6500523);
Maps.googleMap.setCenter(latLng);
return;
}
Maps.paths = paths;
//console.log(Maps.paths);
Maps.wayPoints = [];
for (pathIndex in Maps.paths) {
Maps.wayPoints[pathIndex] = [];
}
for (pathIndex in Maps.paths) {
for (addressIndex in Maps.paths[pathIndex]) {
Maps.getLatLong(Maps.paths[pathIndex][addressIndex], pathIndex, Maps.addWaypoint);
}
}
},
addWaypoint: function(pathIndex, latLng, address) {
// console.log("pathIndex: " + pathIndex);
if (latLng === null) {
Maps.googleMap.setCenter(new google.maps.LatLng(32.1574351, -82.90712300000001));
return;
}
// console.log("callback - latLng: " + latLng.toString());
Maps.wayPoints[pathIndex].push(latLng);
if (Maps.wayPoints[pathIndex].length == Maps.paths[pathIndex].length) {
if (typeof console !== "undefined") {
console.log("Address: " + address);
console.log(Maps.wayPoints[pathIndex]);
console.log("Color: " + Maps.colors[pathIndex - 1]);
}
Maps.setShipmentPath(Maps.wayPoints[pathIndex], Maps.colors[pathIndex - 1]);
}
var marker = new google.maps.Marker({
position: latLng,
map: Maps.googleMap,
title: address,
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 4,
fillColor: Maps.colors[pathIndex - 1],
fillOpacity: 1.0,
strokeColor: Maps.colors[pathIndex - 1]
}
});
Maps.googleMap.setCenter(latLng);
},
setShipmentPath: function (wayPoints, color) {
var lineSymbol = {
path: 'M 0,-1 0,1',
strokeOpacity: 1,
scale: 4
};
var shipmentPath = new google.maps.Polyline({
path: wayPoints,
strokeColor: color,
strokeOpacity: 0,
strokeWeight: 10,
geodesic: true,
icons: [{
icon: lineSymbol,
offset: '0',
repeat: '20px'
}]
});
shipmentPath.setMap(Maps.googleMap);
},
getLatLong: function (address, pathIndex, callback) {
// console.log("Address: " + address);
var geocoder = new google.maps.Geocoder();
geocoder.geocode(
{'address': address},
function(results, status) {
var latLng = null;
if (status !== google.maps.GeocoderStatus.OK) {
if (typeof console !== "undefined") {
console.log("Error!");
console.log(status);
}
return;
}
if (results && results.length > 0) {
// console.log("Formatted Address: " + results[0].formatted_address);
// console.log("Lat Long: " + results[0].geometry.location.toString());
latLng = results[0].geometry.location;
if (callback) {
callback(pathIndex, latLng, results[0].formatted_address);
}
}
}
);
}
};
where paths in plotPaths() function is a 2 dimensional array of list of addresses. e.g.
var addresses = new Array();
addresses["1"] = ["London UK EC1", "Paris FR "];
addresses["2"] = ["Vancouver BC CA "];
addresses["3"] = ["Melborne Vic AU "];
addresses["4"] = ["Cape Town ZA "];
addresses["5"] = ["Tokyo JP ", "Seoul Seoul KR 9199"];
For me it ended up being this line of code:
<meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible">
at the top of my HTML header.

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