I've got a script working to add markers to a map with an infowindow. The problem is that the images are tiny, yet when you inspect and hover over the img entity the size is correct, and the blue box that shows where the canvas sits in the main window is correctly proportioned, it's just the actual image takes up a fraction of the canvas.
I've no idea on what is causing this. Using the Developer Tools I've removed all CSS that appears to be affecting it and nothing changes, except if I remove the 100% width, then the canvas goes full size, but the image is still only a fraction of the canvas.
This is the Javascript
var startLat = 20;
var startLng = 0;
var startZoom = 2;
var isAddress = false;
var distributors = [{"logo":"http:\/\/www.elecro.demomycms.co.uk\/eshop\/files\/images\/distributor-logos\/5.jpg","name":"AG Budget Swimming Pool & Spas","contactNumber":"020 89416618","address":"Unit 10 Wilden Industrial Estate\nWilden Lane\nStourport on Severn\nWorcestershire","postcode":"DY13 9JY","latitude":"52.3504","longitude":"-2.26002"}];
var map;
var geocoder;
$(function () {
var mapOptions = {
zoom: startZoom,
center: new google.maps.LatLng(startLat, startLng)
}
var marker, i;
$('#map-canvas').height($('#map-canvas').width() / 2);
var mapOptions = {
zoom: startZoom,
center: new google.maps.LatLng(startLat, startLng)
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
if ( ! isAddress && $('#country').val() > 0) {
GeocodeCountry();
}
for (i = 0; i < distributors.length; i++) {
var $distributor = distributors[i];
var marker = new google.maps.Marker({
position: new google.maps.LatLng($distributor.latitude, $distributor.longitude),
map: map
});
var infowindow = new google.maps.InfoWindow();
marker.html = '<div class="container-fluid" style="width: 300px">\
<h1 class="row-fluid">\
'+($distributor.logo ? '<div class="span3"><img src="'+$distributor.logo+'" style="width: 100%"></div>' : '')+'\
<span class="span9">'+$distributor.name+'</span>\
</h1>\
<div class="row-fluid">\
<div class="span6">'+$distributor.address+'<br>'+$distributor.postcode+'</div>\
<div class="span6">'+($distributor.url ? ''+$distributor.url+'' : '')+'<br>'+$distributor.contactNumber+'</div>\
</div>\
</div>';
google.maps.event.addListener(marker, 'click', (function() {
return function() {
infowindow.setContent(this.html);
infowindow.open(map, this);
}
})(marker, i));
}
});
function GeocodeCountry() {
geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': $('#country').find('option:selected').text()}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
map.fitBounds(results[0].geometry.viewport);
}
});
}
You have probably noticed the Bootstrap 2 code in the HTML, we're using Bootstrap 2 on the site, but I've not included any of the CSS / JS files in the fiddle below and it is still doing the same thing, so it's not Bootstrap affecting it.
You can see a JS fiddle of this here: http://jsfiddle.net/styphon/raLcmbvc/
I've only included one example marker in the JS Fiddle, but on the site there are over 200 and it does the same with all of them. This is the site if you want to see: http://elecro.demomycms.co.uk/distributors.php
Your testing image is huge, and also contains a lot of whitespace on right and bottom: http://www.elecro.demomycms.co.uk/eshop/files/images/distributor-logos/5.jpg
Then you also apply width:100% CSS to your image, so it will be resized to fit the window.
Depending on what you want to achieve, you could either:
User a better image without whitespace
Remove the width:100%
The problem here is that the image which your displaying is itself having large portion of itself as white!
See the link: http://www.elecro.demomycms.co.uk/eshop/files/images/distributor-logos/5.jpg and try saving the image and looking its dimensions. Its a huge 1433x755 size image of which almost 90% area is white background. So remove the extra white background by cropping the image and you be should be good to go. Rest everything seems fine. You can adjust image size in your code line <div class="container-fluid" style="width: 300px"> by giving appropriate width but first change the image.
Related
UPDATE: I have a static solution working right now, but I'd still like to see if it can be improved upon. All of the code is the same aside from the on click event for switching views.
$(document).on('click', '.mobile-toggle a', function (e) {
e.preventDefault();
if (!$(this).hasClass("active")) {
var target = $(this).attr("data-target");
$("#results > div, .mobile-toggle a").removeClass("active");
$(this).addClass("active");
$("#" + target).addClass("active");
}
var center = dmap.getCenter();
google.maps.event.trigger(dmap, 'resize');
dmap.setCenter(center);
dmap.setZoom(12);
});
This gets the map centered properly, which is good. The zoom is also fine, but it doesn't always fit the route. Sometimes the route is too big to fit, and other times the map should probably be zoomed in a little bit more. Is there any way to determine the zoom value that should be used based on the route? I'm fairly certain this is generally supposed to happen on its own, but that doesn't seem to be the case this time around.
Original post below.
I've read a bunch of questions/answers about this, but none of the provided answers seem to do what I'm looking for. I'll try to explain this the best I can.
I'm currently writing a store locator. On desktop, everything looks fine. Mobile is where I run into difficulty because of some changing views (showing/hiding divs). From what I've read, it looks like a lot of people run into a problem where the map is created in a hidden div and then it's displayed incorrectly (e.g. the map only occupies the top left area of the container) when the div is shown.
The layout of the store locator is as follows - after you search for a location, you see a list view of all the results. When you click the 'map view' tab up top, you see a Google maps view with all of the nearby stores on it. This works fine. If you select a store and click 'get directions' from the list view, you see a list view of the directions to get to that store. Likewise, if you select a store and click 'get directions' while in map view, you see a map of the directions. That works fine in both scenarios.
The issue is when I am in a list view, click to get directions, and then switch over from the list view of directions to the map view. The map gets drawn with the correct route and it fills the div just like it should - however, the route is in the top left of the map, and the map itself is zoomed way out. For example, if the route is in the Philadelphia area, the map is so zoomed out that its center is generally around Bermuda. And it's roughly the same spot in Bermuda every time.
Here's the relevant code for the button press between list and map views.
$(document).on('click', '.mobile-toggle a', function (e) {
e.preventDefault();
if (!(this).hasClass("active")) {
var target = $(this).attr("data-target");
$("#results > div, .mobile-toggle a").removeClass("active");
$(this).addClass("active");
$("#" + target).addClass("active");
}
google.maps.event.trigger(dmap, 'resize');
}
dmap is a global variable containing the directions map, and the map itself has these two listeners assigned to it when it is created.
google.maps.event.addListener(dmap, 'idle', function () {
google.maps.event.trigger(dmap, 'resize');
dmapCenter = dmap.getCenter();
});
google.maps.event.addDomListener(window, 'resize', function () {
dmap.setCenter(dmapCenter);
});
This redraws the map and makes sure the center stays the same while the window is resized, but the map itself still isn't focused on the route from location A to location B. I feel like the solution can't be too far from what I've already tried (based on what I've read), but I can't seem to get this working.
Sorry about the wall of text. If there's any other code you think would help potentially answer the question, please let me know. Thanks!
EDIT: As requested, here's the full code that draws the map.
function calcRoute(start, dest) {
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng(lat, lng)
};
var map = new google.maps.Map(document.getElementById('directions-map'), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions'));
var request = {
origin: start,
destination: dest,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
dmap = map;
dmapCenter = map.getCenter();
google.maps.event.addListener(map, 'idle', function () {
google.maps.event.trigger(map, 'resize');
dmapCenter = map.getCenter();
});
google.maps.event.addDomListener(window, 'resize', function () {
map.setCenter(dmapCenter);
});
}
lat and lng are global variables with the latitude and longitude of the search location.
The workflow you are using (IMHO) seems a little odd to me (IMHO), mainly of your choice to initialize a map instance every time you calculate the directions.
I don't know how much this will help since I haven't been able to test it on a mobile device, but below is code to make a google map, render directions between two points, and maintain the map center after the map is resized (test resize by running snippet in full page than resizing the browser window).
var DMAP,
DMAP_RENDERER,
DIRECTIONS_SERVICE;
/*
Run only once when your page loads to ready global components
for any future direction calls.
*/
function initializeDirectionsFeature(){
//set up directions map
var dmapOptions = {
zoom: 4,
center: new google.maps.LatLng(38.8282, -98.5795) //USA center
};
DMAP = new google.maps.Map( $("#map").get(0), dmapOptions);
//set up renderer for directions map
var rendererOptions = {
map: DMAP,
panel: $("#directions").get(0)
};
DMAP_RENDERER = new google.maps.DirectionsRenderer(rendererOptions);
//Initialize the directions service
DIRECTIONS_SERVICE = new google.maps.DirectionsService();
//Trigger map redraw when dom element is resized
google.maps.event.addDomListener(window, 'resize', function () {
google.maps.event.trigger(DMAP, 'resize');
});
//Preserve map perspective when after resize
google.maps.event.addListener(DMAP, 'resize', function () {
var center = DMAP.getCenter();
google.maps.event.addListenerOnce(DMAP, 'center_changed', function () {
DMAP.setCenter( center );
});
});
}
/*
Gets and renders the directions between params.
Params 'from' and 'to' can be either LatLng or
a String that will be geocoded. Param 'renderer'
is the `google.maps.DirectionsRenderer` to use.
*/
function calcDirections(from, to, renderer){
var request = {
origin: from,
destination: to,
travelMode: google.maps.TravelMode.DRIVING
};
DIRECTIONS_SERVICE.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
renderer.setDirections(response);
}
});
}
//for Snippet, actuall run google maps initialize function
initializeDirectionsFeature();
//For Snippet example
$("#query").submit(function(e){
e.preventDefault();
calcDirections(e.target.from.value, e.target.to.value, DMAP_RENDERER)
});
/* just for Snippet, gmap element just needs a height */
html, body {
position: relative;
width: 98%;
height: 98%;
min-height: 500px;
}
#map, #directions {
width: 100%;
height: 40%;
}
.inline-block {
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js">
</script>
<form id="query">
<div class="inline-block">
<label for="from">From:</label>
<input id="from" name="from" value="New York, NY"/>
</div>
<div class="inline-block">
<label for="to">To:</label>
<input id="to" name="to" value="Philadelphia, PA"/>
</div>
<button type="submit">Go</button>
</form>
<div id="map"></div>
<div id="directions">Directions:</div>
I am trying to change the infowindow in Google maps to the smartinfowindow but for some reason the position of the infowindow is wrong. I never had this issue with the standard infowindow, only the smartinfowindow.
I have found that if I remove position: relative using Firefox inspector the map moves to the top left of the window and the smartinfowindows are then in the correct position.
So is there something I'm missing?
I create the markers with the following:
for (var i = 0; i < data.locations.length; i++) {
var dataPhoto = data.locations[i];
var latLng = new google.maps.LatLng(dataPhoto.latitude,dataPhoto.longitude);
latlngbounds.extend( latLng );
var marker = new google.maps.Marker({
position: latLng,
icon: 'http://www.irishcottageholidays.com/images/cottage1.png'
});
listenMarker(map,marker,InfoWindow,dataPhoto.mID)
markers.push(marker);
}
And then to create the smartinfowindow:
function listenMarker (map,marker,InfoWindow,mID){
google.maps.event.addListener(marker, 'click', function() {
load_content(map,this,InfoWindow,mID);
});
function load_content(map,marker,InfoWindow,mID){
var $j = jQuery.noConflict();
$j.ajax({
type : 'GET',
url : '/ajax/map_popup.asp',
data: {
mID : mID
},
success: function(result){
new SmartInfoWindow({position: marker.getPosition(), map: map, content: result});
}
});
}
Originally I created the infowindows using:
InfoWindow.setOptions({
disableAutoPan: true,
maxWidth: 280
});
InfoWindow.setContent(result);
InfoWindow.open(map, marker);
And this worked but now I've changed to the smartinfowindow, it loads the infowindow but not in the right position.
Thanks for all help in advance.
---- EDIT ----
I now have an issue with the smartinfowindow not closing when opening another and have been unable to achieve this so far. Everything I've found so far seem to apply to the standard infowindows and don't work on the smartinfowindow.
Thanks again for all help in advance.
I believe you should change smartinfowindow properties by editing the smartinfowindow.js file.
I've managed to get a solution through Experts Exchange.
Smartinfowindow position solution:
SmartInfoWindow creates a div to contain the content of the infowindow and appends it to the body. It's position is set to absolute relative to the body. It assumes your map is in the top left corner of the document.
The simple solution is to absolute position the SmartInfoWindow relative to the map canvas instead of the body. To do this you must edit the smartinfowindow.js file on line 178.
Instead of:
document.body.appendChild(div);
Replace with:
var mapDiv = document.getElementById("map");
mapDiv.appendChild(div);
With "map" as the id of the div that holds the map.
Remove smartinfowindow when opening a new one:
function listenMarker (map,marker,InfoWindow,mID){
google.maps.event.addListener(marker, 'click', function() {
if ($('#map > div').length > 1) { $('#map >div:last-child').remove(); }
load_content(map,this,InfoWindow,mID);
});
}
Where:
if ($('#map > div').length > 1) { $('#map >div:last-child').remove(); }
was added to my code
It assumes you have jquery on the page already and no other google map add-ons are creating divs inside the map div.
All credit to tommyBoy on Experts Exchange for both solutions.
I have the following page, which by defaults opens a map centered on France:
http://www.villasdirect.com/_admin/dev/Country_MapV3.asp
It does seem to auto zoom to a certain extent, however when I look at France or Germany (just a couple of examples) the countries are not zoomed in close enough. If I search London however, it seems to be pretty much perfect - as in filling the box with a map of London.
You can see the different results here:
http://www.villasdirect.com/_admin/dev/Country_MapV3.asp?l=france
What I am aiming to do is the fill the map with the country, town or region, when selected... possible?
Help appreciated as always!
Here is my code too:
<%#LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
<%
location = request.QueryString("l")
if location = "" then location = "France"
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1- strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
<div id="map" style="width: 800px; height: 600px"></div>
<form onsubmit="showAddress(); return false" action="#">
<input id="search" size="60" type="hidden" value="<%=location%>" />
</form>
<div id="message"></div>
<noscript><b>JavaScript must be enabled in order for you to use Google Maps.</b>
However, it seems JavaScript is either disabled or not supported by your browser.
To view Google Maps, enable JavaScript by changing your browser options, and then
try again.
</noscript>
<script type="text/javascript">
//<![CDATA[
var xmlsource = '<markers><marker Town="Fayence" Region="Provence - Var" type="green" lng="6.694103" lat="43.624076"/><marker Town="La Cadiere d\'Azur" Region="Provence - Var" type="green" lng="5.755173" lat="43.196218"/><marker Town="Villefranche Du PĂ©rigord" Region="South West France" type="green" lng="1.080006" lat="44.62966"/><marker Town="Limetz-Villez" Region="Paris" type="green" lng="1.547366" lat="49.029137"/><marker Town="Boulogne-Billancourt" Region="Paris" type="green" lng="2.237803" lat="48.84325"/><marker Town="Saint-Germain-En-Laye" Region="Paris" type="green" lng="2.0934031" lat="48.8955155"/></markers>'
var myOptions = {
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), myOptions);
var infoWindow = new google.maps.InfoWindow;
$( $.parseXML( xmlsource ) ).find("marker").each(function() {
var lng = $(this).attr('lng');
var lat = $(this).attr('lat');
marker = new google.maps.Marker({
map:map,
draggable:true,
animation: google.maps.Animation.DROP,
position: new google.maps.LatLng(59.32522, 18.07002)
});
});
google.maps.event.addListener(marker, 'click');
// ====== Create a Client Geocoder ======
var geo = new google.maps.Geocoder();
geo.geocode({'address': document.getElementById("search").value}, function (results, status) {
var ne = results[0].geometry.viewport.getNorthEast();
var sw = results[0].geometry.viewport.getSouthWest();
map.fitBounds(results[0].geometry.viewport);
placeMarkers();
});
function placeMarkers(){
var xmlList = $.parseXML(xmlsource);
var markers = $(xmlList).find('marker');
for (var i = 0; i < markers.length; i++) {
var latlng = new google.maps.LatLng(parseFloat($(markers[i]).attr("lat")),
parseFloat($(markers[i]).attr("lng")));
var type = $(markers[i]).attr("type");
var imgnam = "";
if(type == "green") {
imgnam = "http://openmbta.org/images/map/PinDown1Green.png?1306943843";
}else{
imgnam = "http://openmbta.org/images/map/PinDown1.png?1306943843";
}
var img = new google.maps.MarkerImage(
imgnam,
new google.maps.Size(30,35),
new google.maps.Point(0,0),
new google.maps.Point(15,35)
);
//add a link to your xml that can be inserted here where I have http://www.google.com
var html = "<a href='http://www.google.com'>" + $(markers[i]).attr('Region') + ', ' + $(markers[i]).attr('Town') + "</a>";
var marker = new google.maps.Marker({position: latlng, map: map, icon: img, html:html});
var infowindow1 = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'mouseover', function() {
infowindow1.setContent(this.html);
infowindow1.open(map, this);
});
}
}
</script>
</body>
</html>
It's an old question but I think I have an answer. Instead of this:
map.fitBounds(results[0].geometry.viewport);
try this:
map.fitBounds(results[0].geometry.bounds);
According to Google Maps API documentation results.geometry.bounds may return a slightly different viewport. It's not exactly a solution, but it's worth a try.
Moreover, as I understand, Google Maps doesn't have imagery at infinite zoom levels and when fitBounds() is invoked, it will automatically select the highest zoom level that contains the given bounds and at which imagery is available. In your case, the bounds are the border of France and the viewport fits the border of France at the current zoom level. If you go just one zoom level further, the boundaries of France go out of the viewport.
You can change the size of viewport. For a certain size of viewport (I can't say exactly what size) you might achieve a perfect fit. You cited an example of London. I'm sure that for certain viewport sizes, London doesn't perfectly fit the viewport either. So, it's by chance that you came across a viewport size that is perfect for London.
If you still want more zoom, and can't change the viewport size, I suggest you try getZoom() then increment the result by 1 and setZoom(). Then again, that renders the border areas out of the viewport.
Cheerio!
Afaik there is no way of getting the information as to the physical dimensions of an area (be it city/county/country) from google.
If you had a database yourself with the sizes for every city/state/country combo then I guess you could do it with comparisons.
Otherwise, you're pretty much stuck with this one.
First I'm pretty new to Javascript, so sorry if my question comes across poorly.
I'm creating an application in Flash to help users calculate their electrical costs. Then I'm taking this figure and write it to an xml file.
Now I'm looking to open a webpage and show a google map, and there is a rectangle drawn over the map which is generated dynamically from the number generated earlier and stored in the xml file.
I'm completely lost as to places to turn on how to achieve this. I've gotten my map on to my page, and it scales 100% as I want it to, but I can't figure out the dynamic rectangle part at all. Any ideas or pointers in the right direction greatly appreciated.
In this latest version, the XML file
<countries>
<country name="USA" lat="40.0" lng="-100.0" width="30.0"/>
<country name="France" lat="46.6" lng="2.7" width="10"/>
<country name="Germany" lat="51.1" lng="10.1" width="20"/>
</countries>
is loaded as soon as the map tiles finish loading. I could not get the getProjection to be called correctly if I did not wait for tile loading to finish. The docs state that getting the projection needs the map to be initialized, and recommends listening for projection_changed. Both ways work yet I still feel listening to tiles_loaded is safer and if something goes wrong with the xml loading it will get called again if the map is zoomed or panned a noticeable amount.
var map;
var xmlLoaded = false;
function initialize() {
var mapOptions = { center: new google.maps.LatLng(30.0, 0.0), zoom: 2,
mapTypeId: google.maps.MapTypeId.ROADMAP };
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
google.maps.event.addListener(map, 'tilesloaded', loadData);
}
function loadData() {
if(!xmlLoaded) {
$.ajax({
type: "GET",
url: "co2data.xml",
dataType: "xml",
success: function(xml) {
var countries = xml.documentElement.getElementsByTagName("country");
for(var i = 0, country; country = countries[i]; i++) {
var name = country.getAttribute("name");
var lat = parseFloat(country.getAttribute("lat"));
var lng = parseFloat(country.getAttribute("lng"));
var point = map.getProjection().fromLatLngToPoint(new google.maps.LatLng(lat,lng));
// width is really an arbitrary unit, relative to CO2 tonnage.
// equals the side of the drawn square.
// it is measured in google maps points units.
var width = parseFloat(country.getAttribute("width"));
makeCO2Rect(name, point, width);
}
xmlLoaded = true;
}
});
}
}
The rectangle is defined by width in points (the whole world is 256x256 points), so some conversion is needed when assigning their centers to the more conventional LatLng.
function rectParamsToBounds(point, width) {
var ctrX = point.x;
var ctrY = point.y;
var swX = ctrX - (width/2);
var swY = ctrY - (width/2);
var neX = ctrX + (width/2);
var neY = ctrY + (width/2);
return new google.maps.LatLngBounds(
map.getProjection().fromPointToLatLng(new google.maps.Point(swX, swY)),
map.getProjection().fromPointToLatLng(new google.maps.Point(neX, neY)));
}
Finally, a rectangle is created with a country name that goes into a MarkerWithLabel (using v1.1.5 here, you can hotlink to http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerwithlabel/1.1.5/src/markerwithlabel_packed.js though I prefer saving a local copy)
Since dragging a rectangle appears impossible, a marker in its center works as a handle. When it's dragged, the associated rectangle moves with it.
function makeCO2Rect(name, point, width) {
var rect = new google.maps.Rectangle({
map: map,
bounds: rectParamsToBounds(point, width)
});
var marker = new MarkerWithLabel({
map: map,
position: map.getProjection().fromPointToLatLng(new google.maps.Point(point.x, point.y)),
draggable: true,
raiseOnDrag: false,
labelContent: name,
labelAnchor: new google.maps.Point(30, 0),
labelClass: "labels", // the CSS class for the label
labelStyle: {opacity: 1.0}
});
google.maps.event.addListener(marker, 'drag', function(event) {
var newLatLng = event.latLng;
var newPoint = map.getProjection().fromLatLngToPoint(newLatLng);
rect.setBounds(rectParamsToBounds(newPoint, width));
});
}
google.maps.event.addDomListener(window, 'load', initialize);
Styling the labels need to be done both in the .labels CSS class and the constructor, and rectangles have options like stroke color, thickness, opacity, and fill color.
If you just want to place a rectangular shape on the map, you can create a google.maps.Rectangleapi-doc. If you want to create a rectangular label on the map, you may be more interested in the InfoBox Utility Librarywiki-page.
I have a Google map that is showing a number of markers. When the user moves the map, the markers are redrawn for the new boundaries, using the code below:
GEvent.addListener(map, "moveend", function() {
var newBounds = map.getBounds();
for(var i = 0; i < places_json.places.length ; i++) {
// if marker is within the new bounds then do...
var latlng = new GLatLng(places_json.places[i].lat, places_json.places[i].lon);
var html = "blah";
var marker = createMarker(latlng, html);
map.addOverlay(marker);
}
});
My question is simple. If the user has clicked on a marker so that it is showing an open info window, currently when the boundaries are redrawn the info window is closed, because the marker is added again from scratch. How can I prevent this?
It is not ideal, because often the boundaries are redrawn when the user clicks on a marker and the map moves to display the info window - so the info window appears and then disappears again :)
I guess there are a couple of possible ways:
remember which marker has an open info window, and open it again when the markers are redrawn
don't actually re-add the marker with an open info window, just leave it there
However, both require the marker with an open window to have some kind of ID number, and I don't know that this is actually the case in the Google Maps API. Anyone?
----------UPDATE------------------
I've tried doing it by loading the markers into an initial array, as suggested. This loads OK, but the page crashes after the map is dragged.
<script type="text/javascript" src="{{ MEDIA_URL }}js/markerclusterer.js"></script>
<script type='text/javascript'>
function createMarker(point,html, hideMarker) {
//alert('createMarker');
var icon = new GIcon(G_DEFAULT_ICON);
icon.image = "http://chart.apis.google.com/chart?cht=mm&chs=24x32&chco=FFFFFF,008CFF,000000&ext=.png";
var tmpMarker = new GMarker(point, {icon: icon, hide: hideMarker});
GEvent.addListener(tmpMarker, "click", function() {
tmpMarker.openInfoWindowHtml(html);
});
return tmpMarker;
}
var map = new GMap2(document.getElementById("map_canvas"));
map.addControl(new GSmallMapControl());
var mapLatLng = new GLatLng({{ place.lat }}, {{ place.lon }});
map.setCenter(mapLatLng, 12);
map.addOverlay(new GMarker(mapLatLng));
// load initial markers from json array
var markers = [];
var initialBounds = map.getBounds();
for(var i = 0; i < places_json.places.length ; i++) {
var latlng = new GLatLng(places_json.places[i].lat, places_json.places[i].lon);
var html = "<strong><a href='/place/" + places_json.places[i].placesidx + "/" + places_json.places[i].area + "'>" + places_json.places[i].area + "</a></strong><br/>" + places_json.places[i].county;
var hideMarker = true;
if((initialBounds.getSouthWest().lat() < places_json.places[i].lat) && (places_json.places[i].lat < initialBounds.getNorthEast().lat()) && (initialBounds.getSouthWest().lng() < places_json.places[i].lon) && (places_json.places[i].lon < initialBounds.getNorthEast().lng()) && (places_json.places[i].placesidx != {{ place.placesidx }})) {
hideMarker = false;
}
var marker = createMarker(latlng, html, hideMarker);
markers.push(marker);
}
var markerCluster = new MarkerClusterer(map, markers, {maxZoom: 11});
</script>
You should probably create all your markers at an initial stage with your createMarker() method, and store the returned GMarker objects inside an array. Make sure to set the hide: true property in GMarkerOptions when you create your markers, so that they would be created as hidden by default.
Then instead of iterating through places_json.places, you could iterate through your new GMarker array. You would be able to get the coordinates of each marker with the GMarker.getLatLng() method, with which to check if each marker lies within the bounds.
Finally simply call GMarker.show() for markers that lie within the bounds, or GMarker.hide() to hide them.
You would eliminate the expensive destruction/creation of markers on each map movement. As a positive-side effect, this will also solve your GInfoWindow problem.
If you're using that many markers, make sure you use GMarkerManager. It's designed for many markers, with only a few visible at once.
http://mapki.com/wiki/Marker_Optimization_Tips