Javascript Google map api V3 fitbounds with center location - google-maps-api-3

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);
}

Related

map.setCenter and map.Panto will not shift map

I have tried to change the .onchange function multiple times to change map zoom level and center point. Zoom change takes affect, but the map does not change locations.
Any help would be appreciated. I've removed my api key, but otherwise the map will function on its own.
<script>
function detectBrowser() {
var useragent = navigator.userAgent;
var mapdiv = document.getElementById("map");
if (useragent.indexOf('iPhone') != -1 || useragent.indexOf('Android') != -1 ) {
mapdiv.style.width = '100%';
mapdiv.style.height = '100%';
} else {
mapdiv.style.width = '600px';
mapdiv.style.height = '800px';
}
}
function initMap() {
var central = {lat: 39.8282, lng: -98.5795};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: central
});
var fops = 'http://coleprojects.000webhostapp.com/sqteam.png';
document.getElementById("FieldTeamMember").onchange = function() {
map.setZoom(8);
alert(this.value)
map.setCenter(new google.maps.LatLng(this.value));
};
A clue in the javascript console:
InvalidValueError: in property lat: not a number
You need to pass a google.maps.LatLng (or google.maps.LatLngLiteral) to the map.setCenter method:
document.getElementById("FieldTeamMember").onchange = function() {
map.setZoom(8);
var coords=this.value.split(',');
var latLng = new google.maps.LatLng(parseFloat(coords[0]), parseFloat(coords[1]));
map.setCenter(latLng);
};

Show data when Google Maps marker is clicked in markercluster

I am trying to work out how to show custom data when a Google Maps markerclusterer marker is clicked but can't find this documented anywhere.
My markerclusterer code looks like this but my attempt at capturing the click event on a marker is not working:
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,
icon: markerImage
});
markers.push(marker);
}
*/
for (var i = 0; i < numItemsToShow; ++i) {
var latLng = new google.maps.LatLng(itemsToShow[i].lat, itemsToShow[i].long);
var marker = new google.maps.Marker({
position: latLng,
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,
//styles: [{"featureType":"administrative","elementType":"labels.text.fill","stylers":[{"color":"#444444"}]},{"featureType":"administrative.land_parcel","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"landscape","elementType":"all","stylers":[{"color":"#f2f2f2"}]},{"featureType":"landscape.natural","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"poi","elementType":"all","stylers":[{"visibility":"on"},{"color":"#052366"},{"saturation":"-70"},{"lightness":"85"}]},{"featureType":"poi","elementType":"geometry.fill","stylers":[{"saturation":"-100"},{"lightness":"0"}]},{"featureType":"poi","elementType":"labels","stylers":[{"visibility":"simplified"},{"lightness":"-53"},{"weight":"1.00"},{"gamma":"0.98"}]},{"featureType":"poi","elementType":"labels.text","stylers":[{"visibility":"off"}]},{"featureType":"poi","elementType":"labels.icon","stylers":[{"visibility":"off"},{"lightness":"0"}]},{"featureType":"poi.park","elementType":"geometry.fill","stylers":[{"hue":"#3dff00"},{"saturation":"-100"}]},{"featureType":"road","elementType":"all","stylers":[{"saturation":-100},{"lightness":45},{"visibility":"on"}]},{"featureType":"road","elementType":"geometry","stylers":[{"saturation":"-18"}]},{"featureType":"road","elementType":"labels","stylers":[{"visibility":"off"}]},{"featureType":"road.highway","elementType":"all","stylers":[{"visibility":"on"}]},{"featureType":"road.arterial","elementType":"all","stylers":[{"visibility":"on"}]},{"featureType":"road.arterial","elementType":"labels.icon","stylers":[{"visibility":"off"}]},{"featureType":"road.local","elementType":"all","stylers":[{"visibility":"on"}]},{"featureType":"road.local","elementType":"labels.text","stylers":[{"visibility":"off"}]},{"featureType":"transit","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"water","elementType":"all","stylers":[{"color":"#57677a"},{"visibility":"on"}]},{"featureType":"water","elementType":"geometry.fill","stylers":[{"lightness":"40"}]}]
styles: [{"featureType":"water","stylers":[{"visibility":"on"},{"color":"#b5cbe4"}]},
{"featureType":"landscape","stylers":[{"color":"#efefef"}]},
{"featureType":"road.highway","elementType":"geometry","stylers":[{"color":"#83a5b0"}]},
{"featureType":"road.arterial","elementType":"geometry","stylers":[{"color":"#bdcdd3"}]},
{"featureType":"road.local","elementType":"geometry","stylers":[{"color":"#ffffff"}]},
{"featureType":"poi.park","elementType":"geometry","stylers":[{"color":"#e3eed3"}]},
{"featureType":"administrative","stylers":[{"visibility":"on"},{"lightness":33}]},
{"featureType":"road"},
{"featureType":"poi.park","elementType":"labels","stylers":[{"visibility":"on"},{"lightness":20}]},{},
{"featureType":"road","stylers":[{"lightness":20}]}]
});
var refresh = document.getElementById('refresh');
google.maps.event.addDomListener(refresh, 'click', refreshMap);
var clear = document.getElementById('clear');
google.maps.event.addDomListener(clear, 'click', clearClusters);
google.maps.event.addListener(markerClusterer, 'click', function () {
// do something with this marker ...
this.setTitle('I am clicked');
});
refreshMap();
}
function clearClusters(e) {
e.preventDefault();
e.stopPropagation();
markerClusterer.clearMarkers();
}
This works for me (it opens an infowindow when you mouseover the cluster icon, if you click on the cluster icon, the default behavior is to zoom to the cluster bounds, which makes it hard to see the change of the tooltip/title on the cluster icon):
var infoWindow = new google.maps.InfoWindow();
google.maps.event.addListener(markerClusterer, 'mouseover', function (cluster) {
// do something with this cluster ...
infoWindow.setContent("Mouseover<br>"+cluster.getCenter().toUrlValue());
infoWindow.setPosition(cluster.getCenter());
infoWindow.open(map);
});

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

maps.event.trigger Resize( ) not working

I am working on google maps for quite some time, I am familiar with code and how it works, but unable to place the resize event properly that causes my map to render grey tiles on screen.
Please suggest me where exactly need to place the resize event
Here is my code :
bank.atmDetailsSuccess = function(response) {
bank.locate = response;
bank.getAtmStatus();
};
bank.getAtmStatus = function(results, status) {
var status = bank.locate.Status[0].Value0;
locate = bank.locate;
var map;
if (status == bank.constants.STATUS_ERROR) {
var message = locate.Error[0].Value0;
WL.simpledialog.show(message);
} else if (status == bank.constants.STATUS_SESSION_EXPIRED) {
WL.simpledialog.show("Session Expired!!");
} else if (status == bank.constants.STATUS_SUCCESS) {
map = bank.initializeAtm();
google.maps.event.addDomListener(window, 'load', initializeAtm);
google.maps.event.addDomListener(window, "resize", function() {
alert("In");
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
map.setZoom(10);
});
}
};
bank.initializeAtm = function(){
locate = bank.locate;
var firstlat = locate.Stmt[0].Value5;
var firstlong= locate.Stmt[0].Value6;
// var latlng = new google.maps.LatLng(latitude,longitude);
var image = {
//url: bank.constants.MARKER_PATH,
url: 'images/720x720/pin.png',
// This marker is 20 pixels wide by 32 pixels tall.
size: new google.maps.Size(32, 40),
// The origin for this image is 0,0.
origin: new google.maps.Point(0,0),
// The anchor for this image is the base of the flagpole at 0,32.
anchor: new google.maps.Point(0, 32)
};
var myOptions = {
zoom: 10,
center:new google.maps.LatLng(firstlat, firstlong),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map($('#map-canvas')[0], myOptions);
geocoder = new google.maps.Geocoder();
bank.currentposition();
$('#mapbranch').hide();
$('#map-canvas').show();
$('#atm').html("ATM near your current location");
$('#results').html("");
var directionsService = new google.maps.DirectionsService();
MVC.local.directService = directionsService;
directionsRenderer = new google.maps.DirectionsRenderer({
suppressMarkers: true} );
MVC.local.renderer = directionsRenderer;
var n;
for(n=0; n<locate.Stmt.length; n++)
{
var value = locate.Stmt[n];
name = value.Value0,value.Value1;
lat = value.Value5;
lon = value.Value6;
bank.getDistanceFromLatLonInKm(12.919336, 77.502291,lat,lon);
var myLatLng = new google.maps.LatLng(lat,lon);
var marker = new google.maps.Marker({
position: myLatLng,
icon:image,
map: map,
title: name,
zIndex: 1
});
bank.buildInfoWindow(marker,map,value[n]);
}
return map;
};
Note:This is completely working code only problem is rendering works when i resize broswer manually but not resizing while loading. Please don't mind variable names.All function calls are good except resize event.

Google Maps API v3 port

I am trying to port my google api v2 to v3 but it does not work....i get an "Polyline is not defined" error... :/ the old Polyline is GPolyline and the new is new google.maps.Polyline
https://developers.google.com/maps/documentation/javascript/overlays?hl=de-DE#Polylines
var map = "";
var mapConfig = "";
var mapElements = "";
var curActiveMenuButton = "";
var clickHandlerElementCount = "";
//window.onload = function() {
//window.addEvent('domready', function() {
//document.addEvent('domready', function() {
//alert("The DOM is ready.");
//initializeMap();
//});
/*
* function initializeMap()
*
* Initalisierung der Google-Map.
*/
function initializeMap(){
// Karte ins DOM einhängen
map = new google.maps.Map($('map_canvas'), myOptions);
//place the map on the canvas
//map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var latlng = new google.maps.LatLng(51.05758110879136, 10.451431274414062);
// default zoomlevel and center point
var myOptions = {
zoom: 12,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
navigationControl: true,
mapTypeControl: true,
scaleControl: true,
};
// default zoomlevel and center point
var encodedPolyline = new google.maps.Polyline();
// find bounding polyline and recalculate map center
for (var i = 0; i < mapElements.length; i++) {
if (mapElements[i]['titel'] == "nationalparkhainich") {
encodedPolyline = Polyline.fromEncoded({
points: mapElements[i]['pol'],
levels: mapElements[i]['lev']
});
mapCenter = encodedPolyline.getBounds().getCenter();
i = mapElements.length;
}
}
// Kartenmenue initialisieren
//initializeMapMenue();
}
Polyline is indeed not defined. You use it here:
encodedPolyline = Polyline.fromEncoded({
Version 3 doesn't include fromEncoded() — it appears that you need to use the geometry library (which needs to be explicitly loaded separately) and
encodedPolyline.setPath(
google.maps.geometry.encoding.decodePath(mapElements[i]['pol'])
);
[split on to separate lines here for clarity]

Resources