Google Maps Zoom and Description dialog not working right - javascript

Well I'm having a couple problems getting google maps to work using the v3 API.
Look here: [Removed by Poster]
Both maps are, in fact, working but the zoom level seems like it is random. The zoom is set to 12 when the map is initialized. Also, if you click on the marker, the description box is missing corners and is unable to be closed. Here is the javascript functions I am using to activate these maps:
var mapHash = [];
var bound = new google.maps.LatLngBounds();
finishedCoding = false;
function initMap(map_container_div,lat,lng) {
var latlng = new google.maps.LatLng(lat,lng);
var myOptions = {
zoom:12,
center:latlng,
mapTypeId:google.maps.MapTypeId.ROADMAP,
streetViewControl: false
};
var map = new google.maps.Map(document.getElementById(map_container_div), myOptions);
if (!getMap(map_container_div)) {
var mapInfo = {
mapkey:'',
map:'',
geocoder : new google.maps.Geocoder()
};
mapInfo.map = map;
mapInfo.geocoder = new google.maps.Geocoder();
mapInfo.mapKey = map_container_div;
mapHash.push(mapInfo);
}
}
function placeMarker(myAddress, mapId, description, title) {
mapIndex = getMap(mapId)
//alert(myAddress + mapId + map)
mapHash[mapIndex].geocoder.geocode({
'address':myAddress
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
mapIndex = getMap(mapId)
var marker = new google.maps.Marker({
map:mapHash[mapIndex].map,
position:results[0].geometry.location,
title: title
});
bound.extend(results[0].geometry.location);
mapHash[mapIndex].map.fitBounds(bound);
finishedCoding = true;
placeDesc(marker,description,mapId);
}
});
}
function placeDesc(marker,myDesc,mapId) {
mapIndex = getMap(mapId);
var infowindow = new google.maps.InfoWindow({
content: myDesc
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(mapHash[mapIndex],marker);
});
}
function getMap(mapKey) {
for (var i = 0 ; i < mapHash.length ; i++) {
if (mapHash[i].mapKey == mapKey) {
return i;
}
}
return false;
}
function startmap(mapidd,address,description,title,lat,lng) {
initMap(mapidd,lat,lng)
placeMarker(address,mapidd,description,title)
}

by just removeing
body img {
max-width: 520px !important;
height: auto !important;}
from style sheet
http://www.wppassport.com/wp-content/plugins/easyfanpagedesign/default.theme/style.css
your problem is resolved now

Your dialog boxes aren't closing because of a javascript error.
Something is wrong with infowindow.open(mapHash[mapIndex],marker); inside your click listener. It's displaying the window, which makes you think that the error is happening after, but I'm pretty sure it's in the call itself. When I debugged you weren't making an obvious mistake, but I still think that that line of code is the culprit.

I solved this issue myself and am kicking myself for not thinking of this. :)
Just had to add mapHash[mapIndex].map.setZoom(12);
And I removed the following 2 codes:
bound.extend(results[0].geometry.location);
mapHash[mapIndex].map.fitBounds(bound);

Related

Refresh primefaces gmap markers in javascript

I need to refresh, add new markers or remove markers on a primefaces gmap.
By a callBackParam I pass the markers to a javascript in xhtml.
However when the map refreshes, the event overlaySelect is never fired.
ManageBean scope is viewScoped
public void ajaxPoll() {
Marker[] newMarkers = new Marker[mapLoadModel.getMarkers().size()];
for(int i=0;i < newMarkers.length;i++){
newMarkers[i]=mapLoadModel.getMarkers().get(i);
}
RequestContext.getCurrentInstance().addCallbackParam("newMarkers",new Gson().toJson(newMarkers));
logger.info("refresco marcadores");
}
The javascript:
//<![CDATA[
function handleComplete(xhr, status, args){
var gmap = PF('gMapWV').getMap();
for(var i in gmap.markers)
{
gmap.markers[i].setMap(null);
}
gmap.markers.length=0;
var newMarkers = eval('(' + args.newMarkers + ')');
for(var i in newMarkers)
{
var newMarker = newMarkers[i];
var marker = new google.maps.Marker({
id: newMarker.id,
map: gmap,
position: newMarker.latlng,
icon:newMarker.icon,
title:newMarker.title,
clickable:true
});
}
}
// ]]>
And the map:
<p:poll interval="#{manageLoadExecution.refreshInterval}" listener="#{manageLoadExecution.ajaxPoll}" oncomplete="handleComplete(xhr, status, args)" process="#this" />
<p:gmap widgetVar="gMapWV" id="gMapWV" center="#{manageLoadExecution.latitude} , #{manageLoadExecution.longitude}" zoom="#{manageLoadExecution.zoomLevel}" fitBounds="false" type="terrain" model="#{manageLoadExecution.mapLoadModel}" disableDefaultUI="false" styleClass="map" >
<p:ajax event="overlaySelect" listener="#{manageLoadExecution.onMarkerSelect}" />
<p:gmapInfoWindow id="infoWindow" maxWidth="400" >
<p:outputPanel style="text-align: left; display: block; margin: auto; width:370px" >
After refresh the markers are show on screen, but the overlaySelect event is never fired and the infowindow is not open.
I guess that removing all the markers I'm removing some that makes the event not fires.
Please, any help!
Thank you very very much.
I made it!
I missed to add an id the the new marker in javascript scriptlet.
Finally in javascript code I call _render() method to configure markers and listeners.
Here is the javascript scriptlet:
<script>
//<![CDATA[
function handleComplete(xhr, status, args){
var gmap = PF('gMapWV').getMap();
var newMarkers = eval('(' + args.newMarkers + ')');
for(var i in gmap.markers)
{
var oldMarker = gmap.markers[i];
var newMarker = newMarkers[i];
if(newMarker != null){
oldMarker.setPosition(newMarker.latlng);
oldMarker.title=newMarker.title;
oldMarker.setMap(gmap);
oldMarker.id=newMarker.id;
}else{
oldMarker.setMap(null);
}
}
var oldMarkersLength = gmap.markers.length;
var newMarkersLength = newMarkers.length;
for(var i = oldMarkersLength;i < newMarkersLength;i++)
{
var newMarker = newMarkers[i];
var marker = new google.maps.Marker({
position: newMarker.latlng,
title:newMarker.title,
clickable:true,
id:newMarker.id
});
gmap.markers[i]= marker;
}
PF('gMapWV').addOverlays(gmap.markers);
PF('gMapWV')._render();
}
// ]]>
</script>
If the list decrease the size I set the remain markers to null to reuse then if I need it.
I hope this can help anyone stuck with gmap and primefaces.
Thanks everyone for suggestions
Try to do this, it work to me (for those don't want refresh the map):
var gmap = PF('gmap').getMap();
var marker = new google.maps.Marker({
id: json.id,
map: gmap,
position: json.latlng,
icon: json.icon,
title: json.title,
draggable: true,
clickable:true
});
gmap.markers[gmap.markers.length] = marker;
PF('gmap').addOverlay(marker);
PF('gmap').configureMarkers();
PF('gmap').addOverlays(gmap.markers);

Google InfoWindow not loading inside for loop

I have add the following code to a Google Map on a site of mine. The map contains many points pulling from coordinates set in the WordPress backend.
I also want to include some static points which will always stay on the map and am hardcoding their coordinates.
The following is the code I am using and what happens is that the code displays the first marker but not the infobox. Because of this, the code stops and does not continue through the for loop. The issue is at the return function() bit, but I am not sure how to get it working.
var infowindow = new google.maps.InfoWindow({maxWidth: 185});
var setMarker;
var setMarkers = new Array();
var setLocations = [
['<h4>Location1</h4>', 53.4264,-6.2499, '/wp-content/themes/path/to/airport_icon.png'],
['<h4>Location2</h4>', 53.3461,-6.2969, '/wp-content/themes/path/to/train_icon.png'],
['<h4>Location3</h4>', 53.3532,-6.2468, '/wp-content/themes/path/to/train_icon.png'],
['<h4>Location4</h4>', 53.4264,-6.2499, '/wp-content/themes/path/to/dvc_icon.png'],
['<h4>Location5</h4>', 53.4264,-6.2499, '/wp-content/themes/path/to/dvc_icon.png'],
];
for (var i = 0; i < setLocations.length; i++) {
marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(setLocations[i][1], setLocations[i][2]),
icon : setLocations[i][3],
});
setMarkers.push(setMarker);
google.maps.event.addListener(setMarker, 'click', (function(setMarker, i) {
return function() {
infowindow.setContent(setLocations[i][0]);
infowindow.open(map, setMarker);
}
})(setMarker, i));
}
Define your setMarker variable inside the for loop and push it to your markers array:
for (var i = 0; i < setLocations.length; i++) {
var setMarker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(setLocations[i][1], setLocations[i][2])
});
google.maps.event.addListener(setMarker, 'click', (function (setMarker, i) {
return function () {
infowindow.setContent(setLocations[i][0]);
infowindow.open(map, setMarker);
}
})(setMarker, i));
setMarkers.push(setMarker);
}
JSFiddle demo

How to toggle between KML/KMZ layers in Google Maps api v3

I'm developing a web page with a Google maps application. Currently, I have a functional search bar and map that displays three KML/KMZ layers. I need to be able to toggle between each of the layers, either display one of them, two of them or all three. There is a similar function in Google Earth, but I need it in Google Maps. How can I do this?
Here is my code for the map and search bar:
<script type="text/javascript">
var geocoder;
var map;
var marker;
function initialize() {
geocoder = new google.maps.Geocoder ();
var latlng = new google.maps.LatLng (40.43, -74.00);
var myOptions = {
zoom: 5,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
marker = new google.maps.Marker({map:map});
var ctaLayer = new google.maps.KmlLayer('http://dl.dropbox.com/u/80233620/NY_Radar_data.kmz');
ctaLayer.setMap(map);
var ctaLayer = new google.maps.KmlLayer('http://www.nyc.gov/html/dot/downloads/misc/cityracks.kml');
ctaLayer.setMap(map);
var ctaLayer = new google.maps.KmlLayer('http://dl.dropbox.com/u/80233620/OKX_Radar_data%20(1).kmz');
ctaLayer.setMap(map);
}
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);
marker.setPosition(results [0].geometry.location);
map.setZoom(14);
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
It's simply setMap(null) to hide one, setMap(map) to show. I keep a global array variable layers, to keep track of which layer to toggle:
var layers = [];
layers[0] = new google.maps.KmlLayer('http://dl.dropbox.com/u/80233620/NY_Radar_data.kmz',
{preserveViewport: true});
layers[1] = new google.maps.KmlLayer('http://www.nyc.gov/html/dot/downloads/misc/cityracks.kml',
{preserveViewport: true});
layers[2] = new google.maps.KmlLayer('http://dl.dropbox.com/u/80233620/OKX_Radar_data%20(1).kmz',
{preserveViewport: true});
The preserveViewport option stops the map from jumping around when the layers are toggled.
Here's the function to toggle:
function toggleLayer(i) {
if(layers[i].getMap() === null) {
layers[i].setMap(map);
}
else {
layers[i].setMap(null);
}
}
Note it's using the global variable. Finally the HTML, you can use checkboxes or buttons, and even a radio button by setting only one active layer at first and enabling the right one when the radio set is updated.
Large weather <input type="checkbox" id="layer0" onclick="toggleLayer(0)" checked>
<input type="button" id="layer1" onclick="toggleLayer(1)" value="Racks">
Small weather <input type="checkbox" id="layer2" onclick="toggleLayer(2)" checked>
The whole demo is here, controls on top left of map: http://jsbin.com/irahef/edit#preview
Heiter's answer is good but a little addition to the code in the jsbin example, if you want to have the layers be undisplayed on initialization is to change
layers[i].setMap(map);
to
layers[i].setMap(null);
and then make sure your checkboxes are unchecked.
I tried the code posted above by Heitor, and noticed that clicking the layers on and off changes the order that they are displayed on the map. I implemented this solution to preserve the order of the layers, but it might be somewhat inefficient. If anyone has any suggestions please share.
function toggleLayer(i) {
var j;
for (j = 0; j < layers.length ; j++ )
{
if (j != i)
{
if (layers[j].getMap() === null)
{
layers[j].setMap(null);
} else {
layers[j].setMap(map);
}
} else { //toggle the selected layer
if (layers[j].getMap() === null)
{
layers[j].setMap(map);
} else {
layers[j].setMap(null);
}
}
}
}

Google Maps Api v3 - Multiple Info Windows with custom content

I have finally managed to add multiple markers with custom icons to my Googlemap.
The next step would be to add an individual Infowindow for each marker.
Unfortunatelly i cant figure out how.
Here is my script so far:
<script type="text/javascript">
var offender_locations = [
["10010", "http://localhost/safenation/img/map_offender_icon.png"],
["10001", "http://localhost/safenation/img/map_visitor_icon.png"]
];
var myOptions = {zoom: 10,center: latlng,mapTypeId: google.maps.MapTypeId.ROADMAP};
var map = new google.maps.Map(document.getElementById("elementid"), myOptions);
var latlng = new google.maps.LatLng(0, 0);
var marker;
var i;
for (i = 0; i < offender_locations.length; i++) {
var infowindow = new google.maps.InfoWindow();
var geocoder_map = new google.maps.Geocoder();
var address = offender_locations[i][0];
var icon = offender_locations[i][1];
geocoder_map.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: map.getCenter(),
icon: icon
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(offender_locations[i][1]);
infowindow.open(map, marker);
}
})(marker, i));
} else {alert("The requested offender is not mappable !")};});
}
</script>
I think there now is a problem with the loop. When i try:
var icon = offender_locations[1][1];
all icons are "map_offender_icon.png"
When I use :
var icon = offender_locations[i][1];
nothing changes and all icons are still "map_offender_icon.png"
It seems the var offender_locations[i][1]; is not changing accordingly. The var offender_locations[i][0]; changes accordingly.
Your marker variable is local to your for loop which is not visible outside the loop so the statement
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', (function(marker, i)
is not able to set the listener for your marker.
Best way is include your Info window initialization inside your loop to set listeners to your entire markers.
Hope this helps.
The problem has been solved!
Working script:
Javascript Loop - 2nd variable Not Displaying
(Extracted from edit to the original question)

Google Maps JS v3: Map display: none; after map initialization causing corrupted map

This certainly touches on previous questions regarding map display during initialization. Yet the issue here is with map display being set to none after map should have already initialized. The last line of my widow.onload sets the map to display: none; The map initialization should have already completed by that time, but the fact remains, the final call is causing the problem.
window.onload(); function...
window.onload = function(){
changeTheme(me); // do it now so current_theme is avaible to switchTabs();
switchTabs("tab3"); // sets map div visible
initMaps(); // map initialization. code included.
loadFavoritePlaces(); // asynch $getJSON call, adds markers. No matter the condition of map, markers appear in their proper locations.
closePopup("images");
closePopup("location"); // sets maps.mini_map display: none; Problems if we loadUserTable() later. Otherwise OK. Odd!
closePopup("tweet");
centerDiv();
document.title = '#'+me.screen_name+' - PithyTwits.com';
users[me.id_str] = me;
getPage(); // asynch $.getJSON loads tweets. Not an issue.
// Append a scroll event handler to tweet_div
$("#tweet_div").scroll(function() {
var pos = $(this)[0].scrollHeight - $(this).scrollTop();
if(pos != prev_scroll){ // hack to prevent scroll function from firing twice
prev_scroll = pos;
if (pos == $(this).outerHeight()) {
$("#throbber").fadeIn();
getPage();
}
}
});
loadUserTable(me.id_str);
/* loadUserTable(); calls switchTabs("tab1"); which sets map div display: none;
if I comment this out the map initialization completes properly, but my 'tab1'
doesn't get populated properly. And page doesn't start on 'tab1', which is required. */
// end window.onload()
}
initMaps(); function...
function initMaps() {
// markers list
maps.markers = new Object;
// visibility status'
maps.markerStatus = new Object;
maps.markerStatus['query'] = true;
maps.markerStatus['tweet'] = true;
maps.markerStatus['favorite'] = true;
// define marker images
maps.reticleImage = new google.maps.MarkerImage('images/reticle.png',
new google.maps.Size(63, 63),
new google.maps.Point(0,0),
...
Declarations removed to streamline post.
...
new google.maps.Point(0,0),
new google.maps.Point(1, 13));
maps.markerShape = {
type: "poly",
coords: [9,22,16,11,16,5,11,1,6,1,2,5,2,11,9,22]
}
// setup map options
var latlng = new google.maps.LatLng(39.520427, -94.770621);
var latlng2 = new google.maps.LatLng(46.1912, -122.1944);
var myOptions = {
zoom: 3,
center: latlng,
mapTypeId: google.maps.MapTypeId.HYBRID
};
var myOptions2 = {
zoom: 13,
center: latlng2,
disableDefaultUI: true,
draggable: false,
keyboardShortcuts: false,
mapTypeControl: false,
scrollwheel: false,
mapTypeId: google.maps.MapTypeId.HYBRID
};
// initialize maps
maps.main_map = new google.maps.Map(document.getElementById("map_div"), myOptions);
maps.mini_map = new google.maps.Map(document.getElementById("mini_map"), myOptions2);
// default map center markers
maps.mini_map_marker = new google.maps.Marker({
position: latlng2,
map: maps.mini_map,
icon: maps.favoriteMarker,
shadow: maps.markerShadow,
});
maps.reticleMarker = new google.maps.Marker({
position: latlng,
map: maps.main_map,
shape: reticleShape,
icon: maps.reticleImage,
});
// event handlers
google.maps.event.addListener(maps.main_map, 'zoom_changed', mapZoomed);
google.maps.event.addListener(maps.main_map, 'bounds_changed',
function(){maps.reticleMarker.setPosition(maps.main_map.getCenter());});
//idle event listener provided by #Guan in the marked answer.
google.maps.event.addListenerOnce(maps.main_map, 'idle', function() {
var div = document.getElementById("tab3_content");
div.style.display = "none";
div.style.position = "relative";
div.style.left = "0px";
});
// initialize controls
var controls = document.getElementById("visibility_controls");
maps.main_map.controls[google.maps.ControlPosition.TOP_CENTER].push(controls);
controls.style.display = "inline";
var controls = document.getElementById("control_controls");
maps.main_map.controls[google.maps.ControlPosition.RIGHT_CENTER].push(controls);
controls.style.display = "inline";
var controls = document.getElementById("query_controls");
maps.main_map.controls[google.maps.ControlPosition.BOTTOM_CENTER].push(controls);
controls.style.display = "inline";
}
If I call loadUserTable(); at the end of window.onload(); I get this... (munged)
If I don't call loadUserTable(); at the end of window.onload(); I get this... (correct)
Since the problem stems from the maps display being set to none after the maps should have initialized, it would lead one to believe that the map initialization is actually happening non-syncronously. So how do I know when it is finished, and it is safe to hide the maps div? And also there is the question of why the mini_map seems to be dependent on visibility of the main_map, rather than its own visibility? I get the same results in both Chrome and Firefox, on Linux.
Any help is help :)
Skip
UPDATE: I changed the final call to setTimeout("loadUserTable();", 1000); and 1 second is enough of a pause to let things work, but isn't what I want! Since #Jobsz verifies this is known issue, I'm going to resort to off screen initialization, and move the map into position either when needed for display, or hide it and put it in position after a short timeout.
SOLUTION: Provided by #Guan (Checked answer)
I did not want the map visible during initialization. But wanted it initialized and ready when the user chose that tab.
The map div is initially set thus...
id="tab3_content" style="display: block;position: absolute; left: -1000px;"
That makes it visible, but offscreen to the left.
And then set a listener for the idle event in the map initialization...
google.maps.event.addListenerOnce(maps.main_map, 'idle', function() {
var div = document.getElementById("tab3_content");
div.style.display = "none";
div.style.position = "relative";
div.style.left = "0px";
});
That event fires once when the map is idle(ready). It hides the div and moves it into position on screen.
The loadUserTable() function is called in the normal program flow, and life is good. :)
Could you try calling
//map hold's a reference to your current map
google.maps.event.trigger(map, 'resize');
After the map/div containing it becomes visible?
google.maps.event.addListenerOnce(map, 'idle', function() {
$('#addstop').css({
display: 'none',
left: '0',
top: '0'
});
});
This event happens only once after the map is fully loaded and 'idle'
Yup -- I had this same problem.
What I did was trigger the initialization after the event button that displays the hidden map is clicked.
So I have a hidden div, when it's clicked to shown, i display it and then initalize it. Is this doable for what you're trying to achieve? I'm assuming you want performance in that you'd prefer the click to instantly show a populated map -- however it isn't too slow to populate the small area you're tying to if you do it on the click event.
Just this may help you.
I just have an application that uses tabs mixed with gmap divs.
I was fix same problems. Console just show corruption image message. Your ideas help a lot!
I just use this
$("#tab-3").click(function(){
$(".tab-3").removeClass("ui-screen-hidden");
$(".tab-1").addClass("ui-screen-hidden");
$(".tab-2").addClass("ui-screen-hidden");
initializedonationlocation();
})
function initializedonationlocationdr() {
var directionsDisplay = new google.maps.DirectionsRenderer();
geocoder2 = new google.maps.Geocoder();
infowindow2 = new google.maps.InfoWindow();
var myOptions = {
zoom: 10,
center: new google.maps.LatLng(38.7,-121.59),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map2 = new google.maps.Map(document.getElementById('my_map_donation_donationreceipt'),
myOptions);
google.maps.event.addListener(map2, 'click', function(e) {
geocoder.geocode(
{'latLng': e.latLng},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
if (marker2) {
marker2.setPosition(e.latLng);
} else {
marker2 = new google.maps.Marker({
position: e.latLng,
map: map2});
}
infowindow2.setContent(results[0].formatted_address);
var postCode = extractFromAdress(results[0].address_components, "postal_code");
var street = extractFromAdress(results[0].address_components, "route");
var town = extractFromAdress(results[0].address_components, "locality");
var country = extractFromAdress(results[0].address_components, "country");
var state = extractFromAdress(results[0].address_components, "administrative_area_level_1");
$("#city_donationdr").val(town);
$("#state_donationdr").val(state);
$("#zip_donationdr").val(postCode);
$("#address_donationdr").val(street);
infowindow2.open(map2, marker2);
// Changing window
var prevSelection3 = $("#tabmap").val();
var newSelection3 = $("#navbar2 ul li").children("a").attr("data-tab-class");
$("."+prevSelection3).addClass("ui-screen-hidden");
$("."+newSelection3).removeClass("ui-screen-hidden");
prevSelection3 = newSelection3;
$("#tabmap").val(prevSelection3);
document.getElementById('geocoding').innerHTML = "";
$("#coords_donationdr").val(e.latLng);
$("#address_donationdr").focus();
GetCurbSideCoordsDR(directionsDisplay,map2);
} else {
document.getElementById('geocoding').innerHTML =
'No results found';
}
} else {
document.getElementById('geocoding').innerHTML =
'Geocoder failed due to: ' + status;
}
});
});
}
I only call initialization only when tab that contain gmap is showed. NOT before. Many forums show gmap initialization at pages loading. In conbination with tabs, just only call initialization after tab appears.

Categories