This question already has answers here:
Center/Set Zoom of Map to cover all visible Markers?
(4 answers)
Closed 6 years ago.
I am not a java programmer but I am using some code I found to create a map with multiple markers on so that I can display it within my application. I want the map to be positioned so that it is in the centre of all the markers zoomed out to see them all. I have found some code that that should do this but I don't know where to put it within the code I have. I am also a little unsure if the code i have is good and efficient. Any help would be most appreciated. The code I believe I need is
var markers = [];//some array
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
bounds.extend(markers[i].getPosition());
}
map.fitBounds(bounds);
and my code is.....
var locations = [
['C1',-36.8604268000000,174.8360801000000,13140,'521 3131','E','Keith','','',6.72],
['C2',-36.9127356000000,174.9177729000000,16638,'535 5710','E','Debra','d#xtra.co.nz','027 1234546',15.59],
['C3',-36.9045042000000,174.8237394000000,28477,'725 5566','E','Yolande','y#a.kiwi.nz','027 1234546',8.31],
['C4',-36.8945087000000,174.8511699000000,25075,'70 5055','E','Vanessa','accounts#b.co.nz','027 1234546',9.44],
['C5',-36.9045042000000,174.8237394000000,25854,'25 5566','E','Yolande','z#f.kiwi.nz','027 1234546',8.31],
['C6',-36.8845042000000,174.8499481000000,21292,'7 3056','E','Paul','p#xtra.co.nz','027 1234546',8.79],
['C7',-36.8927054000000,174.8331774000000,30664,'06695791777','Not Rated','Jackie','admin#xyz.kiwi','027 1234546',8.01],
['C8',-36.9046501000000,174.8236843000000,25146,'789 525 3123','E','Debra','','02027 1234546',8.31],
['C9',-36.9338100000000,174.8967737000000,23342,'9274 4620','E','Janneane','j#adn.co.nz','',15.29],
['C10',-36.9222589000000,174.8529857000000,21336,'333 0793','E','Cynthia','cynthia#vt.co.nz','027 123 935',11.53],
['Test Client',-36.8484597000000,174.7633315000000,13983,'0652988421','E','Mickey Mouse','r#xyz.com','',0.10],
['Test Client 9 ACC',-36.8484597000000,174.7633315000000,27264,'8956398842','E','Matt','kn#ec.com','021 288 9999311',0.10],
['Test Client 6',-36.9316457000000,174.5736167000000,23605,'33 814 9577','E','John','ward#xtra.co.nz','027893068',19.17],
['Test Client 7',-36.8658161000000,174.5801917000000,22566,'44 232 0082','E','Yolanda','sw#stu.co.nz','02374585',16.33],
];
function initialize() {
var myOptions = {
center: new google.maps.LatLng(-36.8484480000000,174.7621910000000),
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("default"),
myOptions);
setMarkers(map,locations)
}
function setMarkers(map,locations){
var marker, i
for (i = 0; i < locations.length; i++)
{
var name = locations[i][0]
var lat = locations[i][1]
var long = locations[i][2]
var code = locations[i][3]
var phone = locations[i][4]
var rating = locations[i][5]
var contact = locations[i][6]
var contactemail = locations[i][7]
var contactmobile = locations[i][8]
var Kms = locations[i][9]
latlngset = new google.maps.LatLng(lat, long);
var marker = new google.maps.Marker({
map: map, title: name , position: latlngset
});
map.setCenter(marker.getPosition())
var content = "Client: " + name + '</p>' + '</h3>' + "Client No: " + code + '</p>' + '</h3>' + "Telephone: " + phone + '</p>' + '</h3>' + "Rating: " + rating + '</p>' + '</h3>' + "Contact Name: " + contact + '</p>' + '</h3>' + "Contact Email: " + contactemail + '</p>' + '</h3>' + "Contact Mobile: " + contactmobile + '</p>' + '</h3>' + "Kms From Start Point: " + Kms
var infowindow = new google.maps.InfoWindow()
google.maps.event.addListener(marker,'click', (function(marker,content,infowindow){
return function() {
infowindow.setContent(content);
infowindow.open(map,marker);
};
})(marker,content,infowindow));
}
}
}
var markers = []; //some array
var locations = [
['C1', -36.8604268000000, 174.8360801000000, 13140, '521 3131', 'E', 'Keith', '', '', 6.72],
['C2', -36.9127356000000, 174.9177729000000, 16638, '535 5710', 'E', 'Debra', 'd#xtra.co.nz', '027 1234546', 15.59],
['C3', -36.9045042000000, 174.8237394000000, 28477, '725 5566', 'E', 'Yolande', 'y#a.kiwi.nz', '027 1234546', 8.31],
['C4', -36.8945087000000, 174.8511699000000, 25075, '70 5055', 'E', 'Vanessa', 'accounts#b.co.nz', '027 1234546', 9.44],
['C5', -36.9045042000000, 174.8237394000000, 25854, '25 5566', 'E', 'Yolande', 'z#f.kiwi.nz', '027 1234546', 8.31],
['C6', -36.8845042000000, 174.8499481000000, 21292, '7 3056', 'E', 'Paul', 'p#xtra.co.nz', '027 1234546', 8.79],
['C7', -36.8927054000000, 174.8331774000000, 30664, '06695791777', 'Not Rated', 'Jackie', 'admin#xyz.kiwi', '027 1234546', 8.01],
['C8', -36.9046501000000, 174.8236843000000, 25146, '789 525 3123', 'E', 'Debra', '', '02027 1234546', 8.31],
['C9', -36.9338100000000, 174.8967737000000, 23342, '9274 4620', 'E', 'Janneane', 'j#adn.co.nz', '', 15.29],
['C10', -36.9222589000000, 174.8529857000000, 21336, '333 0793', 'E', 'Cynthia', 'cynthia#vt.co.nz', '027 123 935', 11.53],
['Test Client', -36.8484597000000, 174.7633315000000, 13983, '0652988421', 'E', 'Mickey Mouse', 'r#xyz.com', '', 0.10],
['Test Client 9 ACC', -36.8484597000000, 174.7633315000000, 27264, '8956398842', 'E', 'Matt', 'kn#ec.com', '021 288 9999311', 0.10],
['Test Client 6', -36.9316457000000, 174.5736167000000, 23605, '33 814 9577', 'E', 'John', 'ward#xtra.co.nz', '027893068', 19.17],
['Test Client 7', -36.8658161000000, 174.5801917000000, 22566, '44 232 0082', 'E', 'Yolanda', 'sw#stu.co.nz', '02374585', 16.33],
];
function initialize() {
var myOptions = {
center: new google.maps.LatLng(-36.8484480000000, 174.7621910000000),
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("default"),
myOptions);
setMarkers(map, locations)
}
function setMarkers(map, locations) {
var bounds = new google.maps.LatLngBounds();
var marker, i
for (i = 0; i < locations.length; i++) {
var name = locations[i][0]
var lat = locations[i][1]
var long = locations[i][2]
var code = locations[i][3]
var phone = locations[i][4]
var rating = locations[i][5]
var contact = locations[i][6]
var contactemail = locations[i][7]
var contactmobile = locations[i][8]
var Kms = locations[i][9]
latlngset = new google.maps.LatLng(lat, long);
var marker = new google.maps.Marker({
map: map,
title: name,
position: latlngset
});
map.setCenter(marker.getPosition())
var content = "Client: " + name + '</p>' + '</h3>' + "Client No: " + code + '</p>' + '</h3>' + "Telephone: " + phone + '</p>' + '</h3>' + "Rating: " + rating + '</p>' + '</h3>' + "Contact Name: " + contact + '</p>' + '</h3>' + "Contact Email: " + contactemail + '</p>' + '</h3>' + "Contact Mobile: " + contactmobile + '</p>' + '</h3>' + "Kms From Start Point: " + Kms
var infowindow = new google.maps.InfoWindow()
google.maps.event.addListener(marker, 'click', (function(marker, content, infowindow) {
return function() {
infowindow.setContent(content);
infowindow.open(map, marker);
};
})(marker, content, infowindow));
bounds.extend(marker.getPosition());
}
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#default {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?"></script>
<div id="default"></div>
Below is the code I am working with. I'm trying to fix an error with a map not displaying in all browsers.
In dev tools (chrome), I'm getting a Uncaught ReferenceError: google is not defined error.
$(document).ready(function(){
//google map
function loadGoogleMap() {
var mapOptions = {
scrollwheel: false,
zoom: 14,
mapTypeId: google.maps.MapTypeId.HYBRID
};
var map = new google.maps.Map($("#map")[0], mapOptions);
var bounds = new google.maps.LatLngBounds();
var count = 0;
$.each(dealers, function(ind,dealer){
var point = new google.maps.LatLng(dealer.lat,dealer.lng)
var marker = new google.maps.Marker({
position: point,
map: map,
title: dealer.post_title,
icon: icons[count]
});
var infowindow = new google.maps.InfoWindow({
content:'<div class="infowindow">'+
'<strong>' + dealer.post_title + '</strong><br/>' +
'<address>' +
dealer.address1 + '<br/>' +
dealer.city + ', ' + dealer.state + '<br/>' +
'</address>' +
dealer.phone + '<br/>' +
(dealer.url != '' ? 'Dealer Website<br/>' : '') +
(dealer.email != '' ? 'Email Dealer<br/>' : '') +
'Get Directions'+
'</div>'
});
google.maps.event.addListener(marker,'click',function(){
infowindow.open(map,marker);
});
// add event listener to distributor list
$('#distributors-list li:eq(' + count + ')').click(function(){
infowindow.open(map,marker);
});
bounds.extend(point);
count++;
});
map.fitBounds(bounds);
}
loadGoogleMap();
// reuse fancybox loading icon script
var loadingTimer, loadingFrame = 1;
var locator_animate_loading = function() {
locatorLoading = $('#ajax-loading-overlay');
if (!locatorLoading.is(':visible')){
clearInterval(loadingTimer);
return;
}
$(locatorLoading).css('background-position', '0 ' + (loadingFrame * -40) + 'px');
loadingFrame = (loadingFrame + 1) % 12;
};
$('form.distributor-search').submit(function(e){
locatorLoading = $('#ajax-loading-overlay');
locatorLoading.show();
loadingTimer = setInterval(locator_animate_loading, 66);
$('#locator-content').load(site_url + '/graceports/find-a-distributor?ajax=1&address=' + encodeURIComponent($('#address_search').val()) + ' #ajax-contents', function() {
// load updated list of dealers
$('#locator-content').append('<script src="' + site_url + '/js/dealers.php?address=' + encodeURIComponent($('#address_search').val()) + '"></script>');
loadGoogleMap();
locatorLoading.hide();
});
e.preventDefault();
});
navigator.geolocation.getCurrentPosition(function(position){
$.get(site_url + '/cms/wp-content/themes/grace/inc/latlng-to-zip.php?latlng=' + encodeURIComponent(position.coords.latitude + ' ' + position.coords.longitude), function(data){
$('#address_search').val(data);
$('form.distributor-search').trigger('submit');
});
});
});
You need to wait until google has loaded before running your scripts. Put this somewhere in your document:
$(document).ready(function(){
//google map
function loadGoogleMap() {
var mapOptions = {
scrollwheel: false,
zoom: 14,
mapTypeId: google.maps.MapTypeId.HYBRID
};
var map = new google.maps.Map($("#map")[0], mapOptions);
var bounds = new google.maps.LatLngBounds();
function loadScript() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&' +
'callback=initialize';
document.body.appendChild(script);
}
var count = 0;
$.each(dealers, function(ind,dealer){
var point = new google.maps.LatLng(dealer.lat,dealer.lng)
var marker = new google.maps.Marker({
position: point,
map: map,
title: dealer.post_title,
icon: icons[count]
});
var infowindow = new google.maps.InfoWindow({
content:'<div class="infowindow">'+
'<strong>' + dealer.post_title + '</strong><br/>' +
'<address>' +
dealer.address1 + '<br/>' +
dealer.city + ', ' + dealer.state + '<br/>' +
'</address>' +
dealer.phone + '<br/>' +
(dealer.url != '' ? 'Dealer Website<br/>' : '') +
(dealer.email != '' ? 'Email Dealer<br/>' : '') +
'Get Directions'+
'</div>'
});
google.maps.event.addListener(marker,'click',function(){
infowindow.open(map,marker);
});
// add event listener to distributor list
$('#distributors-list li:eq(' + count + ')').click(function(){
infowindow.open(map,marker);
});
bounds.extend(point);
count++;
});
map.fitBounds(bounds);
}
loadGoogleMap();
// reuse fancybox loading icon script
var loadingTimer, loadingFrame = 1;
var locator_animate_loading = function() {
locatorLoading = $('#ajax-loading-overlay');
if (!locatorLoading.is(':visible')){
clearInterval(loadingTimer);
return;
}
$(locatorLoading).css('background-position', '0 ' + (loadingFrame * -40) + 'px');
loadingFrame = (loadingFrame + 1) % 12;
};
$('form.distributor-search').submit(function(e){
locatorLoading = $('#ajax-loading-overlay');
locatorLoading.show();
loadingTimer = setInterval(locator_animate_loading, 66);
$('#locator-content').load(site_url + '/graceports/find-a-distributor?ajax=1&address=' + encodeURIComponent($('#address_search').val()) + ' #ajax-contents', function() {
// load updated list of dealers
$('#locator-content').append('<script src="' + site_url + '/js/dealers.php?address=' + encodeURIComponent($('#address_search').val()) + '"></script>');
loadGoogleMap();
locatorLoading.hide();
});
e.preventDefault();
});
navigator.geolocation.getCurrentPosition(function(position){
$.get(site_url + '/cms/wp-content/themes/grace/inc/latlng-to-zip.php?latlng=' + encodeURIComponent(position.coords.latitude + ' ' + position.coords.longitude), function(data){
$('#address_search').val(data);
$('form.distributor-search').trigger('submit');
});
});
});
I'm using google maps and rendering many markers at http://www.dentalo.se/search/stockholm and it is working fine.
What I would like to do is when someone clicks on a button I want to use map.SetCenter and focus on that location.
I have a Information button
when a user clicks on it I am calling a JavaScript function and setting the center. But is not working. When I click on information it just becomes gray. You can try it yourself and see what happpenes at http://www.dentalo.se/search/stockholm.
function showCompany(latlong) {
map.setCenter(latlong);
alert(latlong);
}
This is the jquery code for rendering the map
var p = $("#map_search");
var position = p.position();
$("#directionsPanel").css({top: position.top, position:'absolute'});
var map;
var addressField;
var geocoder;
$(document).ready(function () {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(ShowPosition);
}
else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
function showError(error) {
switch (error.code) {
case error.PERMISSION_DENIED:
alert("User denied the request for Geolocation.");
break;
case error.POSITION_UNAVAILABLE:
alert("Location information is unavailable.");
break;
case error.TIMEOUT:
alert("The request to get user location timed out.");
break;
case error.UNKNOWN_ERROR:
alert("An unknown error occurred.");
break;
}
}
function ShowPosition(position) {
//begin rest call
$("#latitude").val(position.coords.latitude);
$("#longitude").val(position.coords.longitude);
var from = $("#latitude").val() + "," + $("#longitude").val();
var urlParts = window.location.href.split('/'),
Id = urlParts[(urlParts.length - 1)];
$.ajax({
type: "GET",
cache: true,
async: false,
url: "/RestService/Dentalo.svc/CompaniesByState/" + Id,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
map = new GMaps({
el: 'map_search',
//center: Id,
lat: data[0].State.Latitude ,//position.coords.latitude,
lng: data[0].State.Longitude,
zoom: 14,
zoomControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DEFAULT,
position: google.maps.ControlPosition.RIGHT_RIGHT
},
panControl: true,
panControlOptions: {
position: google.maps.ControlPosition.RIGHT_TOP
},
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE,
position: google.maps.ControlPosition.RIGHT_TOP
},
panControl: true,
scrollwheel: true
});
map.addMarker({
lat: position.coords.latitude,
lng: position.coords.longitude,
title: 'Min position',
icon: 'http://www.dentalo.se/assets/img/map/user_x64.png'
});
var h = "";
$.each(data, function (index, item) {
var to = item.Latitude + "," + item.Longitude;
h += "<div class='row buttons-page'>" +
"<div class='col-md-8 col-sm-4'>" +
"<h4>"+ item.Name + "</h4>" +
"<p style='margin: 1px;'>" + item.Address + ", " + item.County.Name + "</p>" +
"<p style='margin: 1px;'>" + item.Phone + "</p>" +
"<p style='margin: 1px;'>Distans: " + calcRoute(from, to) + "</p>" +
"</div>" +
"<div class='col-md-3 col-sm-9'>" +
"<div class='btn-group'>" +
"<a href='/booking/"+ item.CompanyId +"' class='btn " + bookable(item.Status) + " " + SetDisplayClass(item.Status) +"'>Boka <i class='m-icon-swapright m-icon-white'></i></a>" +
"<button type='button' class='btn default' onClick='showCompany('" + to + "');return false;'>Information <i class='icon-info-sign m-icon-white'></i></button>" +
"</div>" +
"</div>" +
"</div>" +
"<hr style='margin: 1px;' />";
map.addMarker({
lat: item.Latitude ,
lng: item.Longitude ,
title: item.Address ,
icon: GetMarkerImage(item.Status),
infoWindow: {
content: '<div style="width: 300px"><h4>' + item.Name + '</h4><br /><p>' + item.Address + ', ' + item.County.Name + '</p><div class="four columns alpha"><a class="btn blue ' + SetDisplayClass(item.Status) + '" href="/booking/' + item.CompanyId + '" ><i class="m-icon-swapright m-icon-white"></i> Boka</a> Information</div></div>',
}
})
});
$("#search_panel").html(h).show();
},
error: function (msg, url, line) {
//alert('error trapped in error: function(msg, url, line)');
alert('msg = ' + msg + ', url = ' + url + ', line = ' + line);
}
});
//end rest call
// Define Gecoder
geocoder = new google.maps.Geocoder();
// Init searchbox
initSearchBox();
// main directions
}
How can I set SetCenter when a user clicks on the "Information" button?
Thanks in advance.
map.setCenter(latlong);
latlong must be a google.maps.LatLng object but in your case you are passing a string to your function.
<button onclick="showCompany('59.3618356,18.0140273');return false;">Information</button>
So that won't work.
Instead try:
<button onclick="showCompany('59.3618356','18.0140273');return false;">Information</button>
And
function showCompany(lat, lng) {
var position = new google.maps.LatLng(lat, lng);
map.setCenter(position);
alert(lat, lng);
}