Related
I have a main menu and an item to access the map view. for the first time the map is run according to expectation. the map also can zoom in-out, centerOnMe, and I can give a marker to the position. But when I move or drag the map, the map view was close suddenly and back to main menu. and when I try to access the map again, the map view show but with the main menu view half of it.
Here is my js code :
angular.module('starter.controllers')
.controller('LokasiBayarCtrl', function($scope, $ionicLoading, $location, $compile) {
$scope.go = function(path) {
$location.path(path);
};
var map, infoWindow, mapservice,
myLatlng = new google.maps.LatLng(-33.8668283734, 151.2064891821),
mapOptions = {
//center: myLatlng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
},
iconsBase = 'img/marker/',
icons = {
atm: { icon: iconsBase + 'pln.png' }
};
// Marker + infowindow + angularjs compiled ng-click
var contentString = "<div><a ng-click='clickTest()'>Click me!</a></div>";
var compiled = $compile(contentString)($scope);
var mapHeight = Math.round( 3 / 5 * window.SCREEN_HEIGHT );
mapHeight = ( window.SCREEN_HEIGHT < 500 ) ? 240 : mapHeight;
$scope.mapHeight = mapHeight;
console.log("map height: " + mapHeight + " screenH: " + window.SCREEN_HEIGHT);
function loading(){
$ionicLoading.show({
content: 'Getting current location...',
showBackdrop: false //true
});
}
function loadingDone(){ $ionicLoading.hide(); }
function centerOnMe(){
if(!$scope.map) {
return;
}
loading();
function successCb(pos) {
myLatlng = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
$scope.map.setCenter(myLatlng);
var myPosMarker = new google.maps.Marker({
position: map.getCenter(),
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 10
},
draggable: false,
map: map
});
console.log(pos.coords);
console.log('centerOn Me :', map);
searchPlaces();
loadingDone();
}
function errorCb_highAccuracy(error){
console.log('errorCb_highAccuracy : Unable to get location: ' + error.message);
if (error.code == error.TIMEOUT) {
// Attempt to get GPS loc timed out after 5 seconds,
// try low accuracy location
console.log("attempting to get low accuracy location");
navigator.geolocation.getCurrentPosition(
successCb,
errorCb_lowAccuracy,
{maximumAge:600000, timeout:10000, enableHighAccuracy: false});
return;
}
var msg = "Can't get your location (high accuracy attempt). Error = ";
if (error.code == 1)
msg += "PERMISSION_DENIED";
else if (error.code == 2)
msg += "POSITION_UNAVAILABLE";
msg += ", msg = "+error.message;
loadingDone();
console.log(msg);
}
function errorCb_lowAccuracy(error){
var msg = "Can't get your location (low accuracy attempt). Error = ";
if (error.code == 1)
msg += "PERMISSION_DENIED";
else if (error.code == 2)
msg += "POSITION_UNAVAILABLE";
else if (error.code == 3)
msg += "TIMEOUT";
msg += ", msg = "+error.message;
loadingDone();
console.log(msg);
alert(msg);
}
navigator.geolocation.getCurrentPosition(
successCb, errorCb_highAccuracy, {
maximumAge:600000, timeout:5000, enableHighAccuracy: true
});
}
function initialize() {
console.log('init');
map = new google.maps.Map(document.getElementById("map"),
mapOptions);
infoWindow = new google.maps.InfoWindow({
content: compiled[0]
});
mapservice = new google.maps.places.PlacesService(map);
$scope.map = map;
google.maps.event.addListener(map, 'bounds_changed', searchPlaces);
google.maps.event.addListener(map, 'zoom_changed', searchPlaces);
google.maps.event.addListener(map, 'center_changed', searchPlaces);
google.maps.event.addListener(map, 'resize', searchPlaces);
google.maps.event.addListener(map, 'idle', function () {
document.getElementById("map").setAttribute("style", "min-height: 240px; height: "+$scope.mapHeight+"px; position: relative; background-color: rgb(229, 227, 223); overflow: hidden; -webkit-transform: translateZ(0px);");
console.log(document.getElementById("map").getAttribute("style"));
var center = map.getCenter();
google.maps.event.trigger(map, 'resize');
map.setCenter(center);
});
centerOnMe();
}
function getPlaceData(result){
return {
name: result.name, address_fmt: result.formatted_address, icon: result.icon, types: result.types,
vicinity: result.vicinity, phone: result.formatted_phone_number, website: result.website
};
}
function searchPlaces(){
console.log('searchPlaces');
// nearby search
var request = {
location: myLatlng,
radius: '1000',
types: ['atm', 'bank'],
rankby: 'prominence'
};
mapservice.nearbySearch(request, searchCb);
}
function searchCb(results, status){
if (status != google.maps.places.PlacesServiceStatus.OK) {
console.log('error');
//alert(status);
console.log(status);
return;
}
console.log(results.length);
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
/*for (var i = 0, result; result = results[i]; i++) {
//if (i < 3) { console.log(result); }
console.log('success');
createMarker(result);
}*/
}
function createMarker(place) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon : icons['atm'].icon
});
google.maps.event.addListener(marker, 'click', function() {
mapservice.getDetails(place, function(result, status) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
console.log(result);
infoWindow.setContent(result.name);
infoWindow.open(map, marker);
$scope.place = getPlaceData(result);
console.log($scope.place);
$scope.$apply(); // ZUL : quick and dirty
});
});
}
//google.maps.event.addDomListener(window, 'load', initialize);
$scope.centerOnMe = function() {
centerOnMe();
};
$scope.clickTest = function() {
alert('Example of infowindow with ng-click')
};
// main
initialize();
$scope.place = null;
});
Please can any one can tell me what's wrong with my code?
Previously I apologize because my english is bad, I would be grateful much if anyone can help me.
I would like to add streetview to each infowindow but I can't figure out how to integrate the code. I tried putting the code where the comments are set and that works half. Still have to learn a lot about programming.
html += '<div id="content" style="width:200px;height:200px;"></div>';
var pano = null;
google.maps.event.addListener(infoWindow, 'domready', function () {
if (pano != null) {
pano.unbind("position");
pano.setVisible(false);
}
pano = new google.maps.StreetViewPanorama(document.getElementById("content"), {
navigationControl: true,
navigationControlOptions: { style: google.maps.NavigationControlStyle.ANDROID },
enableCloseButton: false,
addressControl: false,
linksControl: false
});
pano.bindTo("point", marker);
pano.setVisible(true);
});
I'm using this code:
function load() {
var map = new google.maps.Map(document.getElementById("map_canvas"), {
center: new google.maps.LatLng(41.640078, -102.669433),
zoom: 3,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
downloadUrl("mymap.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + point;
// comment *** streetview here ****
var marker = new google.maps.Marker({
map: map,
position: point
});
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);
});
}
Working example using DOM elements (rather than using string content):
// this variable will collect the html which will eventually be placed in the side_bar
var side_bar_html = "";
// arrays to hold copies of the markers used by the side_bar
var gmarkers = [];
// global "map" variable
var map = null;
var sv = new google.maps.StreetViewService();
var clickedMarker = null;
var panorama = null;
// Create the shared infowindow with three DIV placeholders
// One for a text string, oned for the html content from the xml, one for the StreetView panorama.
var content = document.createElement("DIV");
var title = document.createElement("DIV");
content.appendChild(title);
var streetview = document.createElement("DIV");
streetview.style.width = "200px";
streetview.style.height = "200px";
content.appendChild(streetview);
var htmlContent = document.createElement("DIV");
content.appendChild(htmlContent);
var infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(150, 50),
content: content
});
// A function to create the marker and set up the event window function
function createMarker(latlng, name, html) {
var contentString = html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: name,
zIndex: Math.round(latlng.lat() * -100000) << 5
});
marker.myHtml = html;
google.maps.event.addListener(marker, "click", function() {
clickedMarker = marker;
sv.getPanoramaByLocation(marker.getPosition(), 50, processSVData);
// openInfoWindow(marker);
});
// save the info we need to use later for the side_bar
gmarkers.push(marker);
// add a line to the side_bar html
side_bar_html += '<a href="javascript:myclick(' + (gmarkers.length - 1) + ')">' + name + '<\/a><br>';
}
// This function picks up the click and opens the corresponding info window
function myclick(i) {
google.maps.event.trigger(gmarkers[i], "click");
}
function processSVData(data, status) {
if (status == google.maps.StreetViewStatus.OK) {
var marker = clickedMarker;
openInfoWindow(clickedMarker);
if (!!panorama && !!panorama.setPano) {
panorama.setPano(data.location.pano);
panorama.setPov({
heading: 270,
pitch: 0,
zoom: 1
});
panorama.setVisible(true);
google.maps.event.addListener(marker, 'click', function() {
var markerPanoID = data.location.pano;
// Set the Pano to use the passed panoID
panorama.setPano(markerPanoID);
panorama.setPov({
heading: 270,
pitch: 0,
zoom: 1
});
panorama.setVisible(true);
});
}
} else {
openInfoWindow(clickedMarker);
title.innerHTML = clickedMarker.getTitle() + "<br>Street View data not found for this location";
htmlContent.innerHTML = clickedMarker.myHtml;
panorama.setVisible(false);
// alert("Street View data not found for this location.");
}
}
function initialize() {
// Create the map
// No need to specify zoom and center as we fit the map further down.
map = new google.maps.Map(document.getElementById("map_canvas"), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
streetViewControl: false
});
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
// Read the data from example.xml
// downloadUrl("example.xml", function(doc) {
var xmlDoc = xmlParse(xmlData);
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var point = new google.maps.LatLng(lat, lng);
var html = markers[i].getAttribute("html");
var label = markers[i].getAttribute("label");
// create the marker
var marker = createMarker(point, label, html);
bounds.extend(point);
}
// put the assembled side_bar_html contents into the side_bar div
document.getElementById("side_bar").innerHTML = side_bar_html;
// Zoom and center the map to fit the markers
map.fitBounds(bounds);
// });
}
// Handle the DOM ready event to create the StreetView panorama
// as it can only be created once the DIV inside the infowindow is loaded in the DOM.
var pin = new google.maps.MVCObject();
google.maps.event.addListenerOnce(infowindow, "domready", function() {
panorama = new google.maps.StreetViewPanorama(streetview, {
navigationControl: false,
enableCloseButton: false,
addressControl: false,
linksControl: false,
visible: true
});
panorama.bindTo("position", pin);
});
// Set the infowindow content and display it on marker click.
// Use a 'pin' MVCObject as the order of the domready and marker click events is not garanteed.
function openInfoWindow(marker) {
title.innerHTML = marker.getTitle();
htmlContent.innerHTML = marker.myHtml;
pin.set("position", marker.getPosition());
infowindow.open(map, marker);
}
// This Javascript is based on code provided by the
// Community Church Javascript Team
// http://www.bisphamchurch.org.uk/
// http://econym.org.uk/gmap/
// from the v2 tutorial page at:
// http://econym.org.uk/gmap/basic3.htm
google.maps.event.addDomListener(window, 'load', initialize);
var xmlData = '<markers> <marker lat="43.65654" lng="-79.90138" html="Some stuff to display in the<br>First Info Window" label="Marker One" /> <marker lat="43.91892" lng="-78.89231" html="Some stuff to display in the<br>Second Info Window" label="Marker Two" /> <marker lat="43.82589" lng="-79.10040" html="Some stuff to display in the<br>Third Info Window" label="Marker Three" /></markers> ';
/**
* Parses the given XML string and returns the parsed document in a
* DOM data structure. This function will return an empty DOM node if
* XML parsing is not supported in this browser.
* #param {string} str XML string.
* #return {Element|Document} DOM.
*/
function xmlParse(str) {
if (typeof ActiveXObject != 'undefined' && typeof GetObject != 'undefined') {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.loadXML(str);
return doc;
}
if (typeof DOMParser != 'undefined') {
return (new DOMParser()).parseFromString(str, 'text/xml');
}
return createElement('div', null);
}
html,
body {
height: 100%;
}
<script src="https://maps.google.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<!-- you can use tables or divs for the overall layout -->
<table border="1">
<tr>
<td>
<div id="map_canvas" style="width: 550px; height: 450px"></div>
</td>
<td valign="top" style="width:150px; text-decoration: underline; color: #4444ff;">
<div id="side_bar"></div>
</td>
</tr>
</table>
I'm using mosne map (www.mosne.it/playground/mosne_map)
What I'm trying to do is, whenever user change zoom level < 10 the image will be changed. Here's what I got now:
currently the marker doesn't change whenever user changes zoom level
$.fn.mosne_map = function (options) {
var baseconf = {
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var s_infobox = {
content: "",
disableAutoPan: false,
maxWidth: 0,
pixelOffset: new google.maps.Size(-110, 5),
zIndex: null,
boxStyle: {
background: "url('images/infobox_top.png') top center no-repeat",
opacity: 1,
color: '#fff',
padding: '0',
width: "300px"
},
closeBoxMargin: "16px 4px",
closeBoxURL: "images/infobox_close_hd2.png",
infoBoxClearance: new google.maps.Size(1, 1),
isHidden: false,
pane: "floatPane",
enableEventPropagation: false
};
defaults = {
elements: '#list .maplocation', //links selector
map_opt: baseconf, // custom map options object
clat: -9.460181, // set the lat default map center
clng: 100.988281, // set the lng default map center
mapstyle_name: '', // custom map style label and id
mapstyle: '', // mapstyle object
cluster_styles: {}, // custom cluster icons object
marker_icon: {}, // custom marker icon url,width,height
infowindows: true, // shows infoWindows grabing html from the .infobox element
infobox: false, // enable custom infoWindows using infobox class
infobox_s: s_infobox, // default color scheme for custom infobox container
trigger: 'map_open', // you can set a event trigger for each link/marker
clickedzoom: 15, // set the zoom level when you click the single marker
timeout: 100, // delay between click and zoom on the single marker
mode: 'latlng', // switch mode
wait: 500, // timeout between geocode requests
maxtry: 10, // limit of time to bypass query overlimit
cat_style: {}, // costum icons and click zoom level
fitbounds: false, // on|off fit bounds
defzoom: 3, // default zoom level if fitbounds is off
showzoom: false, // bind current map zoom level event
before: function () {}, // before create map callback
after: function () {}, // after create map callback
afterUpdate: function () {} // after update map callback
};
var settings = $.extend({}, defaults, options);
this.each(function () {
var map_el = $(this);
var the_map_el = $(this).get(0);
//on before
settings.before.apply(map_el);
//init map
var center = new google.maps.LatLng(settings.clat, settings.clng);
var map = new google.maps.Map(the_map_el, settings.map_opt);
var bounds = new google.maps.LatLngBounds();
var markerCluster = new MarkerClusterer(map, null, settings.cluster_styles);
map.setCenter(center);
bounds.extend(center);
map.setZoom(settings.defzoom);
map.setCenter(center);
//apply map style
if (settings.mapstyle_name != '') {
var styledMapOptions = {
name: settings.mapstyle_name
};
var m_MapType = new google.maps.StyledMapType(settings.mapstyle, styledMapOptions);
map.mapTypes.set(settings.mapstyle_name, m_MapType);
map.setMapTypeId(settings.mapstyle_name);
}
// set markers icons
var markerIcon = new google.maps.MarkerImage("http://googlemaps.googlermania.com/img/google-marker-big.png");
// init infowindow
if (settings.infowindows) {
var infowindow = new google.maps.InfoWindow({
maxWidth: 200
});
}
// init infobox
if (settings.infobox) {
var boxText = document.createElement("div");
boxText.style.cssText = settings.infobox_s_txt
boxText.innerHTML = "hello world";
var m_box = new InfoBox(settings.infobox_s);
}
// function create marker
var _createMarker = function (el, latLng, markerIcon, m_name, cat) {
if (cat) {
var c_icon = settings.cat_style[cat]['icon'];
var c_icon_w = settings.cat_style[cat]['width'];
var c_icon_h = settings.cat_style[cat]['height'];
if (c_icon) { //var markerIcon = c_icon;
var markerIcon = new google.maps.MarkerImage(c_icon, null, null, null, new google.maps.Size(c_icon_w, c_icon_h));
}
}
var marker = new google.maps.Marker({
position: latLng,
icon: markerIcon,
flat: true,
title: m_name
});
//extend bounds
bounds.extend(latLng);
// bind click on map trigger event fill infowindow / infobox content on demand
if (settings.infowindows || settings.infobox) {
var content = el.find('.infobox').html();
}
google.maps.event.addListener(marker, 'click', function () {
if (settings.infowindows) {
infowindow.close();
infowindow.setContent(content);
infowindow.open(map, marker);
map.setCentexxxr(marker.getPosition());
}
if (settings.infobox) {
m_box.close();
$(boxText).hide();
m_box.setContent(content);
m_box.open(map, marker);
$(boxText).show("slow");
map.setCentesr(marker.getPosition());
}
el.trigger(settings.trigger);
$(el).parent().find('.active').removeClass('active');
$(el).addClass('active');
setTimeout(function () {
map.setZoom(settings.clickedzoom);
map.panTo(latLng);
marker.setAnimation(google.maps.Animation.DROP);
}, settings.timeout);
});
// trigger click on list
$(el).find('.maplink').unbind("click").bind("click", function (e) {
e.preventDefault();
google.maps.event.trigger(marker, "click");
return false;
});
markerCluster.addMarker(marker);
};
var _m_geocode = function (el, geocoder, address, name, cat, j) {
geocoder.geocode({
'address': address
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
latLng = results[0].geometry.location;
_createMarker(el, latLng, markerIcon, name, cat);
if (settings.fitbounds === true) {
map.fitBounds(bounds);
}
} else {
if (status === "OVER_QUERY_LIMIT") {
setTimeout(function () {
//console.log("trying again "+g_address);
j++;
if (j <= settings.maxtry) {
_m_geocode(el, geocoder, address, name, cat, j);
} else {
$(el).css({
opacity: .35
});
}
}, settings.wait);
} else if (status === "ZERO_RESULTS") {
$(el).css({
opacity: .35
});
}
}
});
}
//
$(map_el).bind('update', function () {
//reset cluster and bounds
markerCluster.clearMarkers();
bounds = null;
bounds = new google.maps.LatLngBounds();
// markers loop
var markers = [];
var w_delay = 0;
if (settings.mode === 'address') {
var geocoder = new google.maps.Geocoder();
}
var totel = $(settings.elements).length;
$(settings.elements).each(function (i) {
// create marker
var el = $(this);
//mode geocoding
if (settings.mode === 'address') {
var mkr = el.data();
var name = $(this).find(".name").text();
var address = $(this).find(".address").text();
setTimeout(function () {
_m_geocode(el, geocoder, address, name, mkr.cat, 0);
}, settings.wait * i);
} else {
// mode latlng
var mkr = el.data();
var latLng = new google.maps.LatLng(mkr.lat, mkr.lng);
_createMarker(el, latLng, markerIcon, mkr.name, mkr.cat);
}
//end of the elements loop
});
if (settings.fitbounds === true) {
// log(bounds);
map.fitBounds(bounds);
if (totel == 1) {
map.setZoom(settings.clickedzoom);
}
if (totel == 0) {
map.setZoom(settings.defzoom);
map.setCenter(center);
}
// map.setCenter(center);
} else {
//map.setZoom(settings.defzoom);
//map.setCenter(center);
};
//callbak afterUpdate
settings.afterUpdate.apply(map_el);
}).trigger('update');
$(map_el).bind('bounds', function () {
map.fitBounds(bounds);
});
// nice zoom status
if (settings.showzoom) {
google.maps.event.addListener(map, 'zoom_changed', function () {
$(map_el).trigger("showzoom", [map.getZoom()]);
});
};
//on after
settings.after.apply(map_el);
return true;
//change markerIcon
google.maps.event.addListener(map, 'zoom_changed', function() {
var zoom = map.getZoom();
if (zoom <= 10) {
var markerIcon = new google.maps.MarkerImage("http://i.stack.imgur.com/B2Vg5.png");
}
else {
var markerIcon = new google.maps.MarkerImage ("http://googlemaps.googlermania.com/img/google-marker-big.png")
}
});
});
};
A simple solution for a single icon(not a single marker, this method will change the icon of all markers, but there is also an option to define category-markers)
This is the code that currently defines the default-icon:
// set markers icons
var markerIcon = new google.maps.MarkerImage("http://googlemaps.googlermania.com/img/google-marker-big.png");
Replace it with this code:
// set markers icons
var markerIcon = new google.maps.MVCObject();
google.maps.event.addListener(map,'zoom_changed',function(){
markerIcon.set('icon',(this.getZoom()<10)
? 'http://www.google.com/mapfiles/marker.png'//url for zoom<10
: 'http://googlemaps.googlermania.com/img/google-marker-big.png'//url for zoom>=10
);
});
google.maps.event.trigger(map,'zoom_changed',{});
The url of markerIcon now will be updated when the zoom changes
To apply the changes to the markers replace this code:
var marker = new google.maps.Marker({
position: latLng,
icon: markerIcon,
flat: true,
title: m_name
});
with.....
var marker = new google.maps.Marker({
position: latLng,
icon: markerIcon.icon,
flat: true,
title: m_name
});
marker.bindTo('icon',markerIcon,'icon') ;
Originally we entered the zoom and coordinates. Now we would like it to auto zoom and auto center. Tried bounds.extend() with map.fitBounds(); map.panToBounds(); and can't seem to get it to zoom and center properly. Original code below. Any help greatly appreciated.
<script>
var mapfunction = function() {
$this = $("#map_canvas");
$zoom_level = ($this.data("gmap-zoom") || 5);
$data_lat = ($this.data("gmap-lat") || 29.895883);
$data_lng = ($this.data("gmap-lng") || -80.650635);
$xml_src = ($this.data("gmap-src") || "xml/gmap/pins.xml");
nvisionhstyleMap = new google.maps.StyledMapType(nightvision_highlight_style, {
name: "Nightvision"
});
function xmlLoadMap() {
var centerLatLng = new google.maps.LatLng($data_lat, $data_lng),
mapOptions = {
zoom: $zoom_level,
center: centerLatLng,
//disableDefaultUI: true,
//mapTypeId : google.maps.MapTypeId.ROADMAP
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.TERRAIN, 'nightvision_highlight_style'
]
}
},
bounds = new google.maps.LatLngBounds(),
infowindow = new google.maps.InfoWindow(),
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
map.mapTypes.set('nightvision_highlight_style', nvisionhstyleMap);
map.setMapTypeId(google.maps.MapTypeId.TERRAIN);
// map.setMapTypeId('metro_style');
$.get($xml_src, function(data) {
// create the Bounds object
var bounds = new google.maps.LatLngBounds();
$(data).find("marker").each(function(){
var eachMarker = jQuery(this),
// grab the address from XML
theAddress = eachMarker.find("address").text(),
mygc = new google.maps.Geocoder(theAddress);
mygc.geocode({'address' : theAddress}, function(results, status) {
var mLat = results[0].geometry.location.lat(),
Long = results[0].geometry.location.lng(),
marker = new google.maps.Marker({
position : new google.maps.LatLng(mLat, Long),
map : map,
icon : ('img/' + eachMarker.find("icons").text() + '.png'),
scrollwheel : false,
streetViewControl : true,
title : eachMarker.find("name").text()
}),
link = "link";
google.maps.event.addListener(marker, 'click', function() {// click
// Setting the content of the InfoWindow
var contentString = '<div id="info-map" style="width:300px; height:85px; padding:0px;"><div>' + '<div style="display:inline-block; width:86px; verticle-align:top; float:left;"><img src=' + eachMarker.find("image").text() + ' class="thumbnail" style="width:80%; verticle-align:top;" /></div>' + '<div style="display:inline-block; width:200px; float:left;"><h4>' + eachMarker.find("name").text() + '</h4><b>' + eachMarker.find("address").text() + '</b><br/>' + '<p><i class="fa fa-fw fa-map-marker"></i>More Info</p>' + '</div></div></div>';
infowindow.setContent(contentString);
infowindow.open(map, marker);
google.maps.event.addListener(map, 'click', function() {
infowindow.close()
})
});
});// end geocode
});// end find marker loop
}); // end get data
} // end xmlLoadMap
// grey
xmlLoadMap();
};
// end pagefunction
// run pagefunction on load
$(window).unbind('gMapsLoaded');
$(window).bind('gMapsLoaded', mapfunction);
window.loadGoogleMaps();
Here is what we tried with `bound.extend'. It changes from the default value but centers it 0,0 instead of to the markers.
<script>
var mapfunction = function() {
$this = $("#map_canvas");
$zoom_level = ($this.data("gmap-zoom") || 5);
$data_lat = ($this.data("gmap-lat") || 29.895883);
$data_lng = ($this.data("gmap-lng") || -80.650635);
$xml_src = ($this.data("gmap-src") || "xml/gmap/pins.xml");
nvisionhstyleMap = new google.maps.StyledMapType(nightvision_highlight_style, {
name: "Nightvision"
});
function xmlLoadMap() {
var centerLatLng = new google.maps.LatLng($data_lat, $data_lng),
mapOptions = {
zoom: $zoom_level,
center: centerLatLng,
//disableDefaultUI: true,
//mapTypeId : google.maps.MapTypeId.ROADMAP
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.TERRAIN, 'nightvision_highlight_style'
]
}
},
bounds = new google.maps.LatLngBounds(),
infowindow = new google.maps.InfoWindow(),
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
map.mapTypes.set('nightvision_highlight_style', nvisionhstyleMap);
map.setMapTypeId(google.maps.MapTypeId.TERRAIN);
// map.setMapTypeId('metro_style');
$.get($xml_src, function(data) {
// create the Bounds object
var bounds = new google.maps.LatLngBounds();
$(data).find("marker").each(function(){
var eachMarker = jQuery(this),
// grab the address from XML
theAddress = eachMarker.find("address").text(),
mygc = new google.maps.Geocoder(theAddress);
mygc.geocode({'address' : theAddress}, function(results, status) {
var mLat = results[0].geometry.location.lat(),
Long = results[0].geometry.location.lng(),
marker = new google.maps.Marker({
position : new google.maps.LatLng(mLat, Long),
map : map,
icon : ('img/' + eachMarker.find("icons").text() + '.png'),
scrollwheel : false,
streetViewControl : true,
title : eachMarker.find("name").text()
}),
link = "link";
bounds.extend(new google.maps.LatLng(mLat, Long));
google.maps.event.addListener(marker, 'click', function() {// click
// Setting the content of the InfoWindow
var contentString = '<div id="info-map" style="width:300px; height:85px; padding:0px;"><div>' + '<div style="display:inline-block; width:86px; verticle-align:top; float:left;"><img src=' + eachMarker.find("image").text() + ' class="thumbnail" style="width:80%; verticle-align:top;" /></div>' + '<div style="display:inline-block; width:200px; float:left;"><h4>' + eachMarker.find("name").text() + '</h4><b>' + eachMarker.find("address").text() + '</b><br/>' + '<p><i class="fa fa-fw fa-map-marker"></i>More Info</p>' + '</div></div></div>';
infowindow.setContent(contentString);
infowindow.open(map, marker);
google.maps.event.addListener(map, 'click', function() {
infowindow.close()
})
});
});// end geocode
});// end find marker loop
}); // end get data
map.fitBounds(bounds);
map.panToBounds(bounds);
} // end xmlLoadMap
// grey
xmlLoadMap();
};
// end pagefunction
// run pagefunction on load
$(window).unbind('gMapsLoaded');
$(window).bind('gMapsLoaded', mapfunction);
window.loadGoogleMaps();
Got it! map.fitBounds() needs to be called before Geocode end. Added address_count++ to geocode and called map.fitBounds() on last marker.
if(address_count == $(data).find("marker").length) {
map.fitBounds(bounds);
map.panToBounds(bounds);
}
});// end geocode
});// end find marker loop
}); // end get data
} // end xmlLoadMap
xmlLoadMap();
};
I am using infobox plugin to create multiple markers with different content - http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/examples/infobox-basic.html
Also I am using the markerclusterer plugin to handle too many markers in the same region - http://gmaps-utility-library-dev.googlecode.com/svn/tags/markerclusterer/1.0/src/markerclusterer.js
All the markers are showing correctly and clustering is working perfect.
The problem. My question is how could I just click one infobox and close the others, and if you select a different one it would open that and close the others.
Here is my current code [updated]: http://jsfiddle.net/henrichro/mqrrA/
<script type="text/javascript" src="<?php echo get_bloginfo('template_directory'); ?>/js/markerclusterer.js"></script>
<script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/tags/infobox/1.1.9/src/infobox.js"></script>
<script type="text/javascript">
// build portfolios list
var portfolios = [
<?php
global $post;
$type = 'portfolio';
$args = array(
'post_type' => $type,
'post_status' => 'publish',
'posts_per_page' => -1,
'caller_get_posts'=> 1
);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post();
$my_id = get_the_ID();
$my_title = get_the_title($my_id);
$my_permalink = get_permalink($my_id);
$site_type = get_the_terms($my_id,'type');
if ( $site_type ) {
foreach ( $site_type as $st ) {
if ( $st->slug == 'cultural' ) {
$icon_type = get_bloginfo('template_directory').'/img/icon_blue.png';
} elseif ( $st->slug == 'natural' ) {
$icon_type = get_bloginfo('template_directory').'/img/icon_green.png';
} else {
$icon_type = get_bloginfo('template_directory').'/img/icon_mixed.png';
}
}
} else {
$icon_type = "marker.setIcon(null)";
}
if (get_post_meta($post->ID,'_my_meta',TRUE)) :
$key_meta = get_post_meta($post->ID,'_my_meta',TRUE);
endif;
if($key_meta[coord_lat] && $key_meta[coord_long]):
$lat = $key_meta[coord_lat];
$long = $key_meta[coord_long];
else :
$lat = '';
$long = '';
endif;
?>
['<?php echo $my_title; ?>', <?php echo $lat; ?>, <?php echo $long; ?>, '<?php echo $icon_type; ?>', '<?php echo $my_permalink; ?>'],
<?php
endwhile;
}
//wp_reset_query();
?>
];
function initialize() {
// pointing the center of the universe
var latlng = new google.maps.LatLng(0, 0);
// setting the map options
var myMapOptions = {
zoom: 2,
center: latlng,
scrollwheel: false,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
// creating the map
var map = new google.maps.Map(document.getElementById("googlemap"),myMapOptions);
// list of the coordinates/positions
var latlnglist = []
// bounding
var bounds = new google.maps.LatLngBounds();
var markers = [],
marker;
// building markers from portfolio list
for (i = 0; i < portfolios.length; i++) {
// marker position
var position = new google.maps.LatLng(portfolios[i][1], portfolios[i][2]);
// extending position into list
latlnglist.push(position);
bounds.extend(position);
// special/custom icon for the marker
var image = portfolios[i][3];
// marker options
var markerOptions = {
position: position,
icon: image,
map: map
}
// creating the marker
marker = new google.maps.Marker(markerOptions);
// creating list of markers
markers.push(marker);
// creating the div for the infobox
var boxText = document.createElement("div");
// infobox options
var infoboxOptions = {
content: boxText
,disableAutoPan: false
,maxWidth: 0
,pixelOffset: new google.maps.Size(-140, 0)
,zIndex: null
,boxStyle: {
background: "url('http://google-maps-utility-library-v3.googlecode.com/svn/tags/infobox/1.1.9/examples/tipbox.gif') no-repeat"
,opacity: 0.75
,width: "280px"
}
,closeBoxMargin: "10px 2px 2px 2px"
,closeBoxURL: "http://www.google.com/intl/en_us/mapfiles/close.gif"
,infoBoxClearance: new google.maps.Size(1, 1)
,isHidden: false
,pane: "floatPane"
,enableEventPropagation: false
};
// infobox css styles
boxText.style.cssText = "border: 1px solid black; margin-top: 8px; background: white; padding: 5px; z-index: 9999";
// infobox content
boxText.innerHTML = "<a href='"+ portfolios[i][4] +"'>"+ portfolios[i][0] +"</a><br><br>Test";
// creating the infobox
markers[i].infobox = new InfoBox(infoboxOptions);
// marker action (click)
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
//infobox.setContent(portfolios[i][0]);
markers[i].infobox.close();
markers[i].infobox.open(map, this);
}
})(marker, i));
}
// defining cluster options
var clusterOptions = {
gridSize: 50,
maxZoom: 15
}
// creating the cluster object
var markerCluster = new MarkerClusterer(map, markers, clusterOptions);
var bounds = new google.maps.LatLngBounds();
for (var i = 0, len = latlnglist.length; i < len; i++) {
bounds.extend(latlnglist[i]);
}
map.fitBounds(bounds);
return markers;
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Not sure how much this helps but my solution was to only use one infowindow. For example, the listener I use for clicking map markers is:
google.maps.event.addListener(marker999, "click", function() {
infowindow.close();
infowindow.setContent('contenthere');
infowindow.open(map, marker999);
});
The above code is written for each marker I have displayed (with the unique marker ID and the specific infowindow content for that marker). Infobox should work similarly.
Working example: http://jsfiddle.net/PwJdM/
I've replaced a little bit the marker action (click) part with this:
// marker action (click)
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
for ( h = 0; h < markers.length; h++ ) {
markers[h].infobox.close();
}
markers[i].infobox.open(map, this);
}
})(marker, i));
Inspired from here: google maps api infobox plugin and multiple markers (almost the same code, removed some unnecesary lines in my case).
Updated the working example on jsfiddle: http://jsfiddle.net/henrichro/mqrrA/
it might be a late answer but I resolved this by triggering a custom event and adding a listener on my boxes. Worked fine for me.
// just before you open your infobox
marker.addListener('click', function () {
google.maps.event.trigger(map, "closeAllInfoboxes");
infobox.open(marker.get('map'), marker);
});
//Add this event listener to your infobox
google.maps.event.addListener(map, 'closeAllInfoboxes', function () {
infobox.close();
});`