maps.event.trigger Resize( ) not working - google-maps-api-3

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.

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

Clustering markers with google maps version 3

I have about 2400 markers that are being displayed on google maps version 3. The problem is that there are too many markers on the map and that is not a good visual representation. What is want to do is group that the markers (i.e. cluster them). I'm experiencing some issues regarding that. Below is my sample code.
function initialize() {
var markers = JSON.parse('<%=ConvertDataTabletoString() %>');
var mapOptions = {
center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
zoom: 2,
mapTypeId: google.maps.MapTypeId.ROADMAP
//marker:true
};
var infoWindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
//Get marker image
var redMarker = 'Images/marker2.png';
var greenMarker = 'Images/g48.png';
var currentMarker;
var gmarkers = [];
for (i = 0; i < markers.length; i++) {
var data = markers[i];
var mag = data.Magnitude;
if (mag < 5) {
currentMarker = greenMarker;
}
else if (mag >= 5) {
currentMarker = redMarker;
};
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: data.title,
icon: currentMarker
});
(function (marker, data) {
//Attaching a click event to the current marker
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent('Magnitude: ' + data.Magnitude + '<br />'
+ 'Location: ' + data.title);
infoWindow.open(map, marker);
});
})(marker, data);
gmarkers.push(marker);
}
}
var markerCluster = new MarkerClusterer(map, gmarkers);
window.onload = function () { initialize();
}
I get a javascript error in your code as posted
Uncaught ReferenceError: map is not defined
on this line:
var markerCluster = new MarkerClusterer(map, gmarkers);
The map variable is local to the initialize function.
That line is outside of the initialize function, so the map variable isn't available to it.
Put it inside the initialize function (but after the markers have been parsed).

Implementing google place autocomplete

This is my code for places autocomplete and search.
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places">
</script>
<script>
var geocoder;
var map;
function initialize() {
var input = document.getElementById('address');
var options = {
componentRestrictions: {country: "in"}
};
var autocomplete = new google.maps.places.Autocomplete(input,options);
geocoder = new google.maps.Geocoder();
//var latlng = new google.maps.LatLng(18.52043030000, 73.85674369999);
var mapOptions = {
zoom: 15,
//center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
map = new google.maps.Map(document.getElementById('googleMap'), mapOptions);
}
function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
This is my html code.
<input id="address" type="textbox" size="30">
<input type="button" value="Search" onclick="codeAddress()">
It is working fine but I dont want to user to click the button. When suggestions appeared, and when user select any of suggestion options, map will have to navigate to that place. How do I do this???
When User select any option from dropdown, map should navigate to that place.
Take a look at this example and the implementation of the place_changed event.
var place = autocomplete.getPlace();
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
}
This way you can pan the map to the location of the autocomplete result.
This is my working code..
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places">
</script>
<script>
var geocoder;
var map;
function initialize() {
var input = document.getElementById('address');
var options = {
componentRestrictions: {country: "in"}
};
var autocomplete = new google.maps.places.Autocomplete(input,options);
geocoder = new google.maps.Geocoder();
//var latlng = new google.maps.LatLng(18.52043030000, 73.85674369999);
var mapOptions = {
zoom: 15,
//center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
map = new google.maps.Map(document.getElementById('googleMap'), mapOptions);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
return;
}
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
marker.setIcon(/** #type {google.maps.Icon} */({
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(35, 35)
}));
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
infowindow.open(map, marker);
});
}
function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Now user can select option from dropdown and map will navigate to that place. And also on search button click.
Hope this might help you
function initialize(){
var mapOptions = {//Map Properties
zoom:12,
center: Bangalore
};
googleMap = new google.maps.Map(document.getElementById('map-holder'),mapOptions);//map-holder is a div which holds map in my html
var defaultBounds = new google.maps.LatLngBounds(//bounds for Bengaluru
new google.maps.LatLng(12.7342888,77.3791981),
new google.maps.LatLng(13.173706,77.8826809)
);
googleMap.fitBounds(defaultBounds);
var input = (document.getElementById('searchInput'));//search input element
googleMap.controls[google.maps.ControlPosition.TOP_LEFT].push(input);//binding it to map
var searchBox = new google.maps.places.SearchBox((input));
google.maps.event.addListener(searchBox, 'places_changed', function() {//triggers when search is performed
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
var bounds = new google.maps.LatLngBounds();
for (var i = 0, place; place = places[i]; i++) {
bounds.extend(place.geometry.location);
//googleMap.fitBounds(place.geometry.viewport);
}
googleMap.fitBounds(bounds);
});
google.maps.event.addListener(googleMap, 'bounds_changed', function() {
var bounds = googleMap.getBounds();
searchBox.setBounds(bounds);
})
}

Google Maps API v3 - set bounds and center not working with Ajax/PHP

I am trying to get the automatic bounds-and-zoom functions in Google Maps API 3 to work with Ajax/PHP-generated markers and having no luck so far. The PHP-gen map works fine (with manual center and zoom) until I add the bounds-related code, which I got from here at stackoverflow. It now just centers at (0,0) in the middle of the ocean and only the first of my markers displays. The former doesn't seem totally surprising based on the initial center declaration of (0,0), but it worked for the original poster and I'm a Javascript noob so don't really know what I'm doing! I would be eternally grateful if someone could spot the problem.
Here's my current code (I've left out the icon definitions to save space):
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(0, 0),
zoom: 10,
mapTypeId: '<?php echo $maptype; ?>'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("gen-xml.php?<?php if($country) echo "country=$country"; if($location) echo "&location=$location"; ?>", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("city");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lon")));
var html = "<div class='infowindow'>" + name + " <br/>" + address + " <br/></div>";
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bounds.extend(myLatLng);
map.fitBounds(bounds);
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
Try
bounds.extend(point);
instead of
bounds.extend(myLatLng);
which seems not to be related to any part of your code

Resources