I have a map toggle that when you open it isn't centered on the map marker. I've searched everything, and tried bunch but cannot solve this issue. The HTML markup looks like this:
<div class="hidden_map_wrapper" data-map_height="450px">
<div class="hidden_map_heading">
<h3>Locate us on map</h3>
</div>
<div id="google_map_1" data-map_type="ROADMAP" data-auto_center_zoom="0" data-lat="40.7782201" data-lng="-73.9733317" data-zoom="13" data-scrollwheel="0" data-maptypecontrol="1" data-pancontrol="1" data-zoomcontrol="1" data-scalecontrol="1" class="google_map" style="height: 450px; width: 100%; position: relative; overflow: hidden; transform: translateZ(0px); background-color: rgb(229, 227, 223);">
//bunch of map HTML data here
</div>
<div class="google_map_marker" data-title="Our Company" data-icon="map_marker.png" data-lat="40.7782201" data-lng="-73.9733317">
</div>
</div>
Inside .google_map there is a map that is generated by api already. Now on click I have:
$(".hidden_map_heading").click(function () {
var $current_map = $(this).next(".google_map");
var map_object = document.getElementById($current_map.attr('id'));
$current_map.slideToggle({
duration : 400,
progress : function () {
google.maps.event.trigger(map_object, 'resize');
}
});
$('html, body').animate({ scrollTop: '+=' + $current_map.parent().data('map_height') }, 400);
});
This works, only I don't have my marker centered. I tried with the entire re initializing of the map, but that totally didn't work. I tried adding
var centerofmap = map_object.getCenter();
google.maps.event.trigger(map_object, 'resize');
map_object.setCenter(centerofmap);
In my progress, but that didn't work (got errors about non existing functions).
I'm a bit confused. Everywhere I look the map_object is something like this:
map = new google.maps.Map(document.getElementById($current_map.attr('id')),
myOptions);
But this would mean that I am initializing the map, and the map is already there, initialized and ready. If I don't hide it, it works perfectly. The code for initializing the map looks like this:
function initialize_gmap($element) {
var myLatlng = new google.maps.LatLng($element.data('lat'),$element.data('lng'));
var auto_center_zoom = ($element.data('auto_center_zoom') == 1 ? true : false);
var scrollwheel = ($element.data('scrollwheel') == 1 ? true : false);
var mapTypeControl = ($element.data('maptypecontrol') == 1 ? true : false);
var panControl = ($element.data('pancontrol') == 1 ? true : false);
var zoomControl = ($element.data('zoomcontrol') == 1 ? true : false);
var scaleControl = ($element.data('scalecontrol') == 1 ? true : false);
var styles = (typeof options !== 'undefined') ? options.custom_map_style : '';
var map_type = google.maps.MapTypeId.ROADMAP;
if ($element.data('map_type') == 'SATELLITE') map_type = google.maps.MapTypeId.SATELLITE;
if ($element.data('map_type') == 'HYBRID') map_type = google.maps.MapTypeId.HYBRID;
if ($element.data('map_type') == 'TERRAIN') map_type = google.maps.MapTypeId.TERRAIN;
var mapOptions = {
zoom: parseInt($element.data('zoom'),10),
center: myLatlng,
mapTypeId: map_type,
styles: jQuery.parseJSON(styles),
scrollwheel: scrollwheel,
mapTypeControl: mapTypeControl,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
position: google.maps.ControlPosition.BOTTOM_CENTER
},
panControl: panControl,
panControlOptions: {
position: google.maps.ControlPosition.RIGHT_CENTER
},
zoomControl: zoomControl,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE,
position: google.maps.ControlPosition.RIGHT_CENTER
},
scaleControl: scaleControl,
scaleControlOptions: {
position: google.maps.ControlPosition.BOTTOM_LEFT
},
streetViewControl: false,
streetViewControlOptions: {
position: google.maps.ControlPosition.RIGHT_CENTER
}
};
var elemnt_id = $element.attr('id');
var bounds = new google.maps.LatLngBounds();
var map = new google.maps.Map(document.getElementById(elemnt_id), mapOptions);
var c = 0;
var markers = [];
var infoWindowContent = [];
var marker_icons = [];
$element.siblings('.google_map_marker').each(function(){
var $marker = $(this);
markers[c] = [$marker.data('title'), $marker.data('lat'),$marker.data('lng'),$marker.data('icon')];
infoWindowContent[c] = ['<div class="info_content">' + '<h3>' + $marker.data('title') + '</h3>' + '<p>' + $marker.html() + '</p>' + '</div>'];
c++;
});
// Display multiple markers on a map
var infoWindow = new google.maps.InfoWindow(), marker, i;
// Loop through our array of markers & place each one on the map
for( i = 0; i < markers.length; i++ ) {
var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0],
icon: markers[i][3]
});
// Allow each marker to have an info window
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.setContent(infoWindowContent[i][0]);
infoWindow.open(map, marker);
}
})(marker, i));
}
if(auto_center_zoom){
map.fitBounds(bounds);
}
}
$('.google_map').each(function(){
google.maps.event.addDomListener(window, 'load', initialize_gmap($(this)));
});
So, what am I missing here? How to make map centered on marker on resize?
Solution
The trick is to put the map as a global object, as sabotero mentioned. This way I can use
$(".hidden_map_heading").click(function () {
var $current_map = $(this).next(".google_map");
$current_map.slideToggle({
duration : 400,
progress : function () {
var centerofmap = map.getCenter();
google.maps.event.trigger(map, 'resize');
map.setCenter(centerofmap);
}
});
$('html, body').animate({ scrollTop: '+=' + $current_map.parent().data('map_height') }, 400);
});
And it will work on resize.
First of all made var map global
var map;
function initialize_gmap($element) {
var myLatlng = new google.maps.LatLng($element.data('lat'),$element.data('lng'));
var auto_center_zoom = ($element.data('auto_center_zoom') == 1 ? true : false);
var scrollwheel = ($element.data('scrollwheel') == 1 ? true : false);
var mapTypeControl = ($element.data('maptypecontrol') == 1 ? true : false);
var panControl = ($element.data('pancontrol') == 1 ? true : false);
var zoomControl = ($element.data('zoomcontrol') == 1 ? true : false);
var scaleControl = ($element.data('scalecontrol') == 1 ? true : false);
var styles = (typeof options !== 'undefined') ? options.custom_map_style : '';
var map_type = google.maps.MapTypeId.ROADMAP;
if ($element.data('map_type') == 'SATELLITE') map_type = google.maps.MapTypeId.SATELLITE;
if ($element.data('map_type') == 'HYBRID') map_type = google.maps.MapTypeId.HYBRID;
if ($element.data('map_type') == 'TERRAIN') map_type = google.maps.MapTypeId.TERRAIN;
var mapOptions = {
zoom: parseInt($element.data('zoom'),10),
center: myLatlng,
mapTypeId: map_type,
styles: jQuery.parseJSON(styles),
scrollwheel: scrollwheel,
mapTypeControl: mapTypeControl,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
position: google.maps.ControlPosition.BOTTOM_CENTER
},
panControl: panControl,
panControlOptions: {
position: google.maps.ControlPosition.RIGHT_CENTER
},
zoomControl: zoomControl,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE,
position: google.maps.ControlPosition.RIGHT_CENTER
},
scaleControl: scaleControl,
scaleControlOptions: {
position: google.maps.ControlPosition.BOTTOM_LEFT
},
streetViewControl: false,
streetViewControlOptions: {
position: google.maps.ControlPosition.RIGHT_CENTER
}
};
var elemnt_id = $element.attr('id');
var bounds = new google.maps.LatLngBounds();
////////////////////////
////// map is global ///
////////////////////////
/////////////////////////
map = new google.maps.Map(document.getElementById(elemnt_id), mapOptions);
var c = 0;
var markers = [];
var infoWindowContent = [];
var marker_icons = [];
$element.siblings('.google_map_marker').each(function(){
var $marker = $(this);
markers[c] = [$marker.data('title'), $marker.data('lat'),$marker.data('lng'),$marker.data('icon')];
infoWindowContent[c] = ['<div class="info_content">' + '<h3>' + $marker.data('title') + '</h3>' + '<p>' + $marker.html() + '</p>' + '</div>'];
c++;
});
// Display multiple markers on a map
var infoWindow = new google.maps.InfoWindow(), marker, i;
// Loop through our array of markers & place each one on the map
for( i = 0; i < markers.length; i++ ) {
var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0],
icon: markers[i][3]
});
// Allow each marker to have an info window
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.setContent(infoWindowContent[i][0]);
infoWindow.open(map, marker);
}
})(marker, i));
}
if(auto_center_zoom){
map.fitBounds(bounds);
}
}
$('.google_map').each(function(){
google.maps.event.addDomListener(window, 'load', initialize_gmap($(this)));
});
then in your progress function :
$(".hidden_map_heading").click(function () {
var $current_map = $(this).next(".google_map");
var map_object = document.getElementById($current_map.attr('id'));
$current_map.slideToggle({
duration : 400,
progress : function () {
google.maps.event.addListener(map, 'resize', function(){
var center = new google.maps.latLng(marker.lat(),marker.lng());
map.setCenter(center);
});
google.maps.event.trigger(map_object, 'resize');
}
});
$('html, body').animate({ scrollTop: '+=' + $current_map.parent().data('map_height') }, 400);
});
Related
I am a student trying to become a java developer in Korea
I want to draw a polyline connecting the markers with a click event, not with directions.
I'll give you an exampleenter image description here
It's not finished yet, but I'll show you what I made
I made a mistake but please understand
What I want is to draw a polyline by connecting two fixed markers.
var map, polyline,markers = new Array();
var stockholm = {lat:45,lng:10}; // 맵 중앙 설정
function initMap(){
// map options
var options = {
zoom:4,
center:stockholm,
streetViewControl: true,
draggable:true,
mapTypeId: "roadmap",
// 맵 기본 컨트롤 설정
mapTypeControl: true,
mapTypeControlOptions: {
position: google.maps.ControlPosition.RIGHT_TOP
},
panControl: true,
panControlOptions: {
position: google.maps.ControlPosition.RIGHT_TOP
},
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL,
position: google.maps.ControlPosition.RIGHT_TOP
},
scaleControl: true
}
// Map 호출 ======================================================================
map = new google.maps.Map(document.getElementById('map'),options);
// polyline 옵션 지정 ============================================================
polyline = new google.maps.Polyline({
strokeColor: 'red',
strokeWeight: 3,
map: map
});
google.maps.event.addListener(map, 'click', function (event) {
addPoint(event.latLng);
});
// searchbox===================
const input = document.getElementById("pac-input");
const searchBox = new google.maps.places.SearchBox(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
let markers1 = [];
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener("places_changed", () => {
const places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers1.forEach((marker) => {
marker.setMap(null);
});
markers1 = [];
// For each place, get the icon, name and location.
const bounds = new google.maps.LatLngBounds();
places.forEach((place) => {
if (!place.geometry || !place.geometry.location) {
console.log("Returned place contains no geometry");
return;
}
const 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(25, 25),
};
// Create a marker for each place.
markers1.push(new google.maps.Marker({
map,
icon,
title: place.name,
position: place.geometry.location,
}));
if (place.geometry.viewport) {
bounds.union(place.geometry.viewport);
}else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
// 고정 마커 추가
var markers = [
// 가나
{
coords:{lat:6.6666004, lng:-1.6162709},
iconImage:'assets/img/places/stparkdublin.png',
content:'<div style="height:auto;width:400px;"><h1>가나-쿠마시</h1>쿠마시는 가나 아샨티 주의 주도이며 구 아샨티 왕국의 수도였다. 수도인 아크라에서 북서쪽으로 약 250km 떨어져 있다. 쿠마시는 적도로부터 북쪽으로 약 482km, 기니만으로터 북쪽으로 약 160km 에 위치한다.',
},
{
coords:{lat:5.6037168,lng:-0.1869644},
iconImage:'assets/img/places/botanic garden.png',
content:'<div style="height:auto;width:400px;"><h1>가나-아크라</h1>아크라는 가나 공화국의 수도이자 약 227만 명의 인구를 가진 가나 최대의 도시이다. 도시 자체도 아크라 메트로폴리스 특구에 속해 있으며, 그 면적은 약 139km²이다. 아크라의 관광지 중에 가나 국립 박물관이 있다. 코토카 국제공항이 있다.',
},
{
coords:{lat:5.1315, lng:-1.2794744},
iconImage:'assets/img/places/stparkdublin.png',
content:'<div style="height:auto;width:400px;"><h1>가나-케이프코스트</h1>케이프코스트는 가나의 항구 도시로, 중앙 주의 주도이다. 16세기부터 영국과 포르투갈, 스웨덴, 덴마크, 네덜란드의 통치를 받았다. 15세기 포르투갈이 이 곳을 발견했으며 1653년 스웨덴이 케이프코스트 성을 건설했다. 이 성은 현재 세계유산으로 지정되어 있다.',
},
{
coords:{lat:9.393908, lng:-0.8556313999999999},
iconImage:'assets/img/places/swordscastle.png',
content:'<div style="height:auto;width:400px;"><h1>가나-타말레</h1>타말레은 가나 북부 주의 주도이다. 인구는 55만명이다.',
},
{
coords:{lat:10.7875419, lng:-0.8579818},
iconImage:'assets/img/places/Howth.png',
content:'<div style="height:auto;width:400px;"><h1>가나-볼가탕가</h1>볼가탕가는 가나의 도시이다. 경작과 가축 사육이 주된 생업이다.',
},
];
var gmarkers = [];
for(var i = 0; i < markers.length; i++){
gmarkers.push(addMarker(markers[i]));
}
const sidebar = document.getElementById("sidebar"); // sidebar
var activeInfoWindow = null;
//Add MArker function
function addMarker(props){
var marker = new google.maps.Marker({
position:props.coords,
map:map,
descrip:props.content,
});
//Check content
if(props.content){
var infoWindow = new google.maps.InfoWindow({
content:props.content
});
marker.addListener('click',function(){
infoWindow.open(map,marker);
for(var i=0;i<markers.length;i++){
sidebar.innerHTML = props.content;
}
});
marker.addListener('click', function () {
if (activeInfoWindow) { activeInfoWindow.close();}
infoWindow.open(map, marker);
activeInfoWindow = infoWindow;
});
}
return marker;
}
var markerCluster = new MarkerClusterer(map, gmarkers,
{
imagePath:'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m',
gridSize:100,
minClusterSize:10,
});
}
google.maps.event.addDomListener(window, 'load', initMap);
//poly line ======================================================================
var latlnglatlng = new Array;
function removePoint(marker) {
for (var i = 0; i < markers.length; i++) {
if (markers[i] === marker) {
markers[i].setMap(null);
markers.splice(i, 1);
polyline.getPath().removeAt(i);
}
}
}
function addPoint(latlng) {
var marker = new google.maps.Marker({
position: latlng,
map: map
});
markers.push(marker);
//console.log(markers.position.lng.Scopes);
polyline.getPath().setAt(markers.length - 1, latlng);
google.maps.event.addListener(marker, 'click', function (event) {
removePoint(marker);
});
}
#map {
height: 100%;
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDjtW34Ax16khc7UYth6--V4pNFX1XlHUE&libraries=places"></script>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js"></script>
Thanks again for watching I really want to solve this, I've been thinking about it for a month
I'm trying to increase page speed by loading my Google Maps two seconds after page load. While doing so, I keep on getting "Cannot read property 'extend' of undefined". I know there is some asynchronous loading going on but I'm not sure how to get it in proper order to get this map to load 2 seconds after the page is done. Any help is greatly appreciated.
Page Code:
<div id="mapCont"></div>
<script defer type='text/javascript' src='/js/maps.js'></script>
maps.js
$(window).bind("load", function() {
$.getScript('https://maps.googleapis.com/maps/api/js?key=key', function()
{
setTimeout(function(){
function doMap(callback) {
$("#mapCont").html('<div id="mapInfoManual" class="searchMap mb5"></div>');
callback();
}
doMap(function() {
initialize();
var map = null;
var markers = [];
var openedInfoWindow ="";
var bounds = new google.maps.LatLngBounds();
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(64.85599578876611, -147.83363628361917),
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
}
};
map = new google.maps.Map(document.getElementById("mapInfoManual"),
mapOptions);
google.maps.event.addListener(map, 'zoom_changed', function() {
zoomChangeBoundsListener = google.maps.event.addListener(map, 'bounds_changed', function(event) {
if (this.getZoom() > 20) // Change max/min zoom here
this.setZoom(18);
google.maps.event.removeListener(zoomChangeBoundsListener);
});
});
addMarker();
}
function addMarker() {
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < markersArray.length; i++) {
CodeAddress(markersArray[i]);
}
}
// Address To Marker
function CodeAddress(markerEntry) {
var mytitle = (markersArray[i]['title']);
var myaddress = (markersArray[i]['address']);
var linkid = (markersArray[i]['linkid']);
var linkurl = (markersArray[i]['linkurl']);
var image = { url: '/images/MapPin.png', };
var lat = markerEntry['lat'];
var long = markerEntry['long'];
// var myLatLng = {lat: markerEntry['lat'], lng: markerEntry['long']};
var myLatlng = new google.maps.LatLng(parseFloat(lat),parseFloat(long));
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
icon: image
});
bounds.extend(marker.getPosition());
var infoWindowContent = "<div class='cityMapInfoPop'><span style='font-weight:700;'>"+ mytitle +"</span><br /><br />" + myaddress + "<br /><br /><a href='/center/" + linkurl + "/'>More Details</a></div>";
openInfoWindow(marker, infoWindowContent);
markers.push(marker);
map.fitBounds(bounds);
}
//Info Window
function openInfoWindow(marker, infoWindowContent) {
var infowindow = new google.maps.InfoWindow({
content: '<div class="cityMapInfoPop">' + infoWindowContent + '</div>'
});
google.maps.event.addListener(marker, 'click', function() {
if (openedInfoWindow != "") {
openedInfoWindow.close();
}
infowindow.open(map, marker);
openedInfoWindow = infowindow;
});
}
});
}, 2000);
});
});
The initial https://maps.googleapis.com/maps/api/js?key=key loads additional scripts that are not being captured by your implementation. The package, https://www.npmjs.com/package/#googlemaps/js-api-loader, enables the following pattern and is probably what you want:
import { Loader } from '#googlemaps/js-api-loader';
const loader = new Loader({
apiKey: "",
version: "weekly",
libraries: ["places"]
});
loader
.load()
.then(() => {
doMap();
initialize();
})
.catch(e => {
// do something
});
Alternative(use callback) if you want JQuery and your existing pattern:
window.callback = () => {
doMap();
initialize();
};
$(window).bind("load", function() {
$.getScript('https://maps.googleapis.com/maps/api/js?key=key&callback=callback', () => {}); // do nothing here
Also related: https://developers.google.com/maps/documentation/javascript/examples/programmatic-load-button
Im trying to load around 600 googlemap markers on page load using the function addMarker.
The page takes a lot of time to load.
Is there anything I can do to make it load faster while keep using the addMarker function?
Thanks.
var map
var myLatlng = new google.maps.LatLng(35.9531719,14.3712201);
var markerBounds = new google.maps.LatLngBounds();
var markers = {};
function HomeControl(controlDiv, map)
{
google.maps.event.addDomListener(zoomout, "click", function() {
var currentZoomLevel = map.getZoom();
if(currentZoomLevel != 0)
{
map.setZoom(currentZoomLevel - 1);
}
});
google.maps.event.addDomListener(zoomin, "click", function() {
var currentZoomLevel = map.getZoom();
if(currentZoomLevel != 21)
{
map.setZoom(currentZoomLevel + 1);
}
});
}
function initialize()
{
var googleMapOptions = {
center: new google.maps.LatLng(35.9531719,14.3712201),
zoom: 11,
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl: false,
streetViewControl: false,
panControl: false,
draggable: true
};
map = new google.maps.Map(document.getElementById("map-canvas"), googleMapOptions);
google.maps.event.addListener(map, "idle", function() {
addMarker(latitude,longitude,id,'Title','url');
});
var homeControlDiv = document.createElement("div");
var homeControl = new HomeControl(homeControlDiv, map);
}
var infowindow = new google.maps.InfoWindow({
content: ""
});
function addMarker(lat,long,id,desc,url)
{
var myIcon = new google.maps.MarkerImage("/images/pips/"+id+".png", null, null, null, new google.maps.Size(28,38));
var myLatlng = new google.maps.LatLng(lat,long);
var marker = new google.maps.Marker({
map: map,
title: desc,
position: myLatlng,
icon: myIcon,
id: id
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent('' + desc + '');
infowindow.setPosition(marker.getPosition());
infowindow.open(map, marker);
});
markers[id] = marker;
markerBounds.extend(myLatlng);
google.maps.event.addListener(marker, "click", function() {
infowindow.open(map,marker);
});
}
google.maps.event.addDomListener(window, "load", initialize);
</script>
You can use clustering, it joins neighbor markers into one, and expand only on zoom
You can do clustering in client side, as well as server side, depending the amount of markers...
I would suggest to use server clustering if amount is more than 4000, otherwise client should look fine
i am trying to add clustering on my map, the code i am using is working fine but there is no clustring on it and can't figure out how should i add the cluster to this code.
(function (namespace, $, undefined) {
// map the namespace to that
var that = namespace;
var markers = [];
var dealers = [];
var googleMap;
var tmpDealer = "";
function AddMarkers(aar, map, show) {
if (aar.length > 0) {
var image = '/Files/Templates/Designs/Mobler/images/MapMarker.png';
for (var i = 0; i < aar.length; i++) {
markers.push( new google.maps.Marker({
position: new google.maps.LatLng(parseFloat( aar[i].Latitude),parseFloat(aar[i].Longitude)),
map: map,
title: aar[i].Name,
icon: image,
DealerId: aar[i].DealerId,
DealerPage: aar[i].Area
}));
}
for (var i = 0; i < markers.length; i++) {
if (show) {
google.maps.event.addListener(markers[i], "click", function () {
tmpDealer = this.DealerPage;
MoblerLandingPage.SetCookie("/Default.aspx" + tmpDealer, false);
MoblerLandingPage.SetAreaName("/Default.aspx?AreaID=" + this.DealerPage, function() {
setTimeout(function() {
var area = $.cookie("MoblerAreaName");
document.location = "http://" + document.domain + "/" + area;
}, 250);
});
});
} else {
google.maps.event.addListener(markers[i], "click", that.onMarkerClick)
}
}
}
}
var InfoBoxOptions2 = {
content: ""
, disableAutoPan: false
, maxWidth: 0
, pixelOffset: new google.maps.Size(-75, -5)
, zIndex: null
, boxClass: "DealerMapInfoBox"
, closeBoxMargin: "5px"
, closeBoxURL: "/Files/Templates/Designs/SmagOgBehag/images/infoBoxClose.png"
, infoBoxClearance: new google.maps.Size(1, 1)
, isHidden: false
, pane: "floatPane"
, enableEventPropagation: false
, alignBottom : true
};
var infoBox2 = new InfoBox(InfoBoxOptions2);
that.Initialize = function(mapId, dealerArray, show){
dealers = dealerArray;
var mapOptions = {
center: new google.maps.LatLng(56.22, 11.32),
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
if(!show){
var mapOptions = {
center: new google.maps.LatLng(56.22, 11.32),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
}
googleMap = new google.maps.Map(document.getElementById(mapId), mapOptions);
if(dealerArray.constructor === Array && dealerArray.length > 0){
AddMarkers(dealers, googleMap, show);
}
if(!show){
google.maps.event.addListener(googleMap, 'click', function () {
infoBox2.close();
});
}
}
that.onMarkerClick = function(){
var marker = this;
infoBox2.content_ = $('#Dealer' + marker.DealerId + ' li a').html();
infoBox2.open(marker.map, marker);
}
that.ShowDealerOnMap = function(dealerId) {
for (var i = 0; i < markers.length; i++) {
if (markers[i].DealerId == dealerId) {
var marker = markers[i];
marker.map.setZoom(15);
marker.map.panTo(marker.getPosition())
infoBox2.content_ = $('#Dealer' + marker.DealerId).html()
infoBox2.open(marker.map, marker);
}
}
}
Did you take a look to this documentation ? You can see a working sample to use MarkerClusterer
//Create your map
var center = new google.maps.LatLng(37.4419, -122.1419);
var options = {
'zoom': 13,
'center': center,
'mapTypeId': google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), options);
//Create the clusterer and its options
var mcOptions = {gridSize: 50, maxZoom: 15};
var markers = [...]; // Create the markers you want to add and collect them into a array.
//Add the clusterer to the map, and the markers to the clusterer.
var mc = new MarkerClusterer(map, markers, mcOptions);
Please note that if you don't have a lot of markers, you'll have to change some options in order to see the clusterer working. Change the maxZoom where the clusterer works, and the size of the grid ( gridSize option).
For a complete list of all options, please refer to this document
See this:
http://www.appelsiini.net/2008/introduction-to-marker-clustering-with-google-maps
You can make clusters, rectangle based or square based.
function addDoctorLocation(options)
{
var gm = Ext.getCmp('mygooglemap');
var mpoint = new google.maps.LatLng(options.lat,options.lng);
var marker = gm.addMarker(mpoint,options.marker,false,false, options.listeners);
infoBubble = new InfoBubble({
map: gm,
content: '<div class="phoneytext">Some label</div>',
//position: new google.maps.LatLng(options.lat, options.lng),
shadowStyle: 1,
padding: '10px',
//backgroundColor: 'rgb(57,57,57)',
borderRadius: 5,
minWidth: 200,
arrowSize: 10,
borderWidth: 1,
borderColor: '#2c2c2c',
disableAutoPan: true,
hideCloseButton: false,
arrowPosition: 7,
backgroundClassName: 'phoney',
pixelOffset: new google.maps.Size(130, 120),
arrowStyle: 2
});
infoBubble.open(map, marker);
}
Success added the marker on map, unfortunately infoBubble nothing has shown? why?
and dont have any error on FireBug
UPDATE HOW TO CALL THE FUNCTION
tree.on('checkchange', function(node){
var data = node.data;
if (data.checked == true){
var lati,longi;
var record = MarkerStore.findRecord('MainID', data.MainID)
if (record){
lati = record.get('Latitude');
longi = record.get('Longitude');
}else{
Ext.MessageBox.show({
title: 'Error !',
msg: 'No Record Found In Database ! <br />',
icon: Ext.MessageBox.INFO
});
}
var options = {
lat:lati,
lng:longi,
marker: {title:"Hello World!"},
listeners: {
click: function(e){
}
},
MainID: data.MainID
}
addDoctorLocation(options);
} else {
markers[data.MainID].setMap(null);
}
})
UPPDATE For #Ankit
var markers = {};
var openedInfoWindow = null;
function addDoctorLocation(options)
{
var gm = Ext.getCmp('mygooglemap');
var mpoint = new google.maps.LatLng(options.lat,options.lng);
var marker = gm.addMarker(mpoint,options.marker,false,false, options.listeners);
markers[options.MainID] = marker;
var infowindow = new google.maps.InfoWindow({
content: 'Hello !',
maxWidth: 200
});
google.maps.event.addListener(marker, 'click', function() {
// added next 4 lines
google.maps.event.addListener(infowindow, 'closeclick', function() {
openedInfoWindow = null;
});
if (openedInfoWindow != null) openedInfoWindow.close(); // <-- changed this
openedInfoWindow = infowindow;
infowindow.open(gm, marker);
});
still can't close the infowindow,when clicked marker get this error
TypeError: b.O is not a function
[Break On This Error]
(82 out of range 43)
function addDoctorLocation(options)
{
var gm = Ext.getCmp('mygooglemap');
var mpoint = new google.maps.LatLng(options.lat,options.lng);
var marker = gm.addMarker(mpoint,options.marker,false,false, options.listeners);
var infowindow = new google.maps.InfoWindow({content: "Some label"});
google.maps.event.addListener(marker, 'click', function(gm,marker) {
infowindow.open(gm, marker); // if still you can not open than use infowindow.open(gm, this)
})
}
but looks like you want to style your infowindow than better use infobox instead of infowindow. Check you about InfoBox ->Styling InfoWindow with Google Maps API
You can add some html tags like br, bold to infowindow content but I think you can not style infowindow.
I try your example with google maps intstance and it works fine:
var markers = {};
var infowindow;
var openedInfoWindow = null;
var centerPointDefault = new google.maps.LatLng(39.739, -98.984);
function DrawMainMap(centerMap) {
var myOptions = {
center: centerMap,
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), myOptions);
}
$(document).ready(function () {
var options = {
lat: centerPointDefault.lat(),
lng: centerPointDefault.lng(),
marker: { title: "Hello World!" },
listeners: {
click: function(e) {
}
}
};
DrawMainMap(centerPointDefault);
addDoctorLocation(options);
}
function addDoctorLocation(options) {
var mpoint = new google.maps.LatLng(options.lat, options.lng);
var marker = new google.maps.Marker({
position: mpoint
});
marker.setMap(map);
var infowindow = new google.maps.InfoWindow({
content: 'Hello !',
maxWidth: 200
});
google.maps.event.addListener(marker, 'click', function() {
// added next 4 lines
google.maps.event.addListener(infowindow, 'closeclick', function() {
openedInfoWindow = null;
});
if (openedInfoWindow != null) openedInfoWindow.close(); // <-- changed this
openedInfoWindow = infowindow;
infowindow.open(map, marker);
});
}