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
Related
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
I am new to Meteor and Javascript. I am creating a map that gives directions from your current location to a marker on the map. Everything seems to work except that I can't seem to call the calcRoute() function correctly. Or maybe it is defined in the wrong place.
I think I need some schooling on template helpers. Please tell me where I went wrong. Thanks.
var gmaps = {
// map object
map: null,
//direction services object
directionsService: null,
//direction services object
directionsDisplay: null,
//direction services object
stepDisplay: null,
markerArray: []
}
Template.map.helpers({
mapOptions: function() {
if (GoogleMaps.loaded()) {
if (!Geolocation.error()) {
pos = Geolocation.latLng();
}
return {
//center: new google.maps.LatLng(-25.2743, 133.7751),
center: new google.maps.LatLng(pos.lat, pos.lng),
zoom: 12,
scaleControl: false,
zoomControl: false,
mapTypeControl: false,
panControl: false,
rotateControl: true,
overviewMapControl: false,
streetViewControl: false,
};
}
},
calcRoute: function() {
//clear markers before calculating function
gmaps.clearMarkers();
console.log(this.markerArray);
// Retrieve the start and end locations and create
// a DirectionsRequest using BICYCLING directions.
var start = marker3.getPosition();
var end = document.getElementById('marketName').value;
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.BICYCLING
};
// Route the directions and pass the response to a
// function to create markers for each step.
this.directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var warnings = document.getElementById('warnings_panel');
warnings.innerHTML = '<b>' + response.routes[0].warnings + '</b>';
this.directionsDisplay.setDirections(response);
gmaps.showSteps(response);
}
});
},
showSteps: function(directionResult) {
// For each step, place a marker, and add the text to the marker's
// info window. Also attach the marker to an array so we
// can keep track of it and remove it when calculating new
// routes.
var myRoute = directionResult.routes[0].legs[0];
for (var i = 0; i < myRoute.steps.length; i++) {
var marker = new google.maps.Marker({
position: myRoute.steps[i].start_location,
map: map.instance
});
gmaps.attachInstructionText(marker, myRoute.steps[i].instructions);
this.markerArray[i] = marker;
}
},
attachInstructionText: function(marker, text) {
// Instantiate an info window to hold step text.
var stepDisplay = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'mouseover', function() {
// Open an info window when the marker is clicked on,
// containing the text of the step.
stepDisplay.setContent(text);
stepDisplay.open(map.instance, marker);
})
google.maps.event.addListener(marker, 'click', function() {
map.instance.setZoom(14);
map.instance.setCenter(marker.getPosition());
stepDisplay.open(map.instance, marker);
})
},
clearMarkers: function() {
// First, remove any existing markers from the map.
for (var i = 0; i < this.markerArray.length; i++) {
this.markerArray[i].setMap(null);
}
// Now, clear the array itself.
this.markerArray = [];
}
});
Template.map.onCreated(function() {
GoogleMaps.ready('map', function(map) {
var bikeLayer = new google.maps.BicyclingLayer();
bikeLayer.setMap(map.instance);
var marker1 = new google.maps.Marker({
position: new google.maps.LatLng(29.71739, -95.40183),
map: map.instance,
title: 'Rice U Farmers Market'
});
var infowindow1 = new google.maps.InfoWindow({
content: ''
});
google.maps.event.addListener(marker1, 'click', function() {
infowindow1.setContent( '<p>Farmers Market at Rice U </p>' +'<button onclick="Meteor.call(calcRoute());">Directions from my Location</button>');
infowindow1.open(map.instance, marker1);
});
var marker2 = new google.maps.Marker({
position: new google.maps.LatLng(29.81063, -95.37999),
map: map.instance,
title: 'Canino\'s Produce'
});
var infowindow2 = new google.maps.InfoWindow({
content: 'Canino\'s Produce'
});
google.maps.event.addListener(marker2, 'click', function() {
infowindow2.open(map.instance, marker2);
});
var image = '/img/app/flag1.png'
var marker3 = new google.maps.Marker({
position: new google.maps.LatLng(pos.lat, pos.lng),
map: map.instance,
title: 'You are here',
icon: image
});
var rendererOptions = {
map: map.instance
}
this.directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
// global flag saying we intialized already
Session.set('map', true);
})
});
You have to pass the name of the method that Meteor will call as a string;
Replace:
'<p>Farmers Market at Rice U </p>' +'<button onclick="Meteor.call(calcRoute());">Directions from my Location</button>');
infowindow1.open(map.instance, marker1);
with:
'<p>Farmers Market at Rice U </p>' +'<button onclick="Meteor.call(\'calcRoute\');">Directions from my Location</button>');
infowindow1.open(map.instance, marker1);
I have a problem with my GeoJson layers which I want to cluster (with MarkerClusterer) and then be able to show and hide them via checkboxes or similar. Therefore I tried something like the code below:
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(52.515696, 13.392624),
zoom: 11,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"),
mapOptions);
var bounds = new google.maps.LatLngBounds();
var barLayer = new google.maps.Data();
var cafeLayer = new google.maps.Data();
barLayer.loadGeoJson('json/eat_drink/bar.geojson');
cafeLayer.loadGeoJson('json/eat_drink/cafe.geojson');
var markerClusterer = new MarkerClusterer(map);
var infowindow = new google.maps.InfoWindow();
markerClusterer.setMap(map);
function displayMarkers(layer) {
var layer = layer;
google.maps.event.addListener(layer, 'addfeature', function (e) {
if (e.feature.getGeometry().getType() === 'Point') {
var marker = new google.maps.Marker({
position: e.feature.getGeometry().get(),
title: e.feature.getProperty('name'),
map: map
});
// open the infoWindow when the marker is clicked
google.maps.event.addListener(marker, 'click', function (marker, e) {
return function () {
var myHTML = e.feature.getProperty('name');
infowindow.setContent("<div style='width:150px; text-align: center;'>"+myHTML+"</div>");
infowindow.setPosition(e.feature.getGeometry().get());
infowindow.setOptions({pixelOffset: new google.maps.Size(0,-30)});
infowindow.open(map, marker);
};
}(marker, e));
markerClusterer.addMarker(marker);
bounds.extend(e.feature.getGeometry().get());
map.fitBounds(bounds);
map.setCenter(e.feature.getGeometry().get());
}
});
layer.setMap(null);
google.maps.event.addListener(map, "click", function () {
infowindow.close();
});
};
document.getElementById('bar').onclick = function(){ // enable and disable markers
if(document.getElementById('bar').checked == true){
displayMarkers(barLayer);
}else{
return null;
}
};
}
Unfortunatley this doesn't work and I don't no exactly why.
If I remove the displayMarkers() function around the code and replace "layer" with the desired GeoJson layer, e.g. "barLayer", it works just fine.
Since I will end up with tons of GeoJason layers I would prefer a "compact" solution like this insted of copying the code multiple times. Have you guys any ideas how to do that properly?
I'm afraid I haven't done much more than refactor your code. Could you give this a try, and if it doesn't work specify exactly what doesn't work?
function displayMarkers(layer, map, markerClusterer) {
google.maps.event.addListener(layer, 'addfeature', function(e) {
if (e.feature.getGeometry().getType() === 'Point') {
var marker = new google.maps.Marker({
position: e.feature.getGeometry().get(),
title: e.feature.getProperty('name'),
map: map
});
// open the infoBox when the marker is clicked
google.maps.event.addListener(marker, 'click', function(e) {
var myHTML = e.feature.getProperty('name');
var infowindow = new google.maps.InfoWindow();
infowindow.setContent("<div style='width:150px; text-align: center;'>" + myHTML + "</div>");
infowindow.setPosition(e.feature.getGeometry().get());
infowindow.setOptions({
pixelOffset: new google.maps.Size(0, -30)
});
infowindow.open(map, marker);
google.maps.event.addListener(map, "click", function() {
infowindow.close();
});
});
markerClusterer.addMarker(marker);
var bounds = new google.maps.LatLngBounds();
bounds.extend(e.feature.getGeometry().get());
map.fitBounds(bounds);
map.setCenter(e.feature.getGeometry().get());
}
});
layer.setMap(null);
}
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(52.515696, 13.392624),
zoom: 11,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var barLayer = new google.maps.Data();
var cafeLayer = new google.maps.Data();
barLayer.loadGeoJson('json/eat_drink/bar.geojson');
cafeLayer.loadGeoJson('json/eat_drink/cafe.geojson');
var markerClusterer = new MarkerClusterer(map);
markerClusterer.setMap(map);
document.getElementById('bar').onclick = function() { // enable and disable streetViewControl
if (document.getElementById('bar').checked == true) {
displayMarkers(barlayer, map, markerClusterer);
} else {
return null;
}
};
}
I have the following code that works as intended except the google.maps.event.addListener(marker, 'click', function(). I am including all the code for reference. You will see the commented out code that I have tried. I want the map to zoom in when the marker is clicked. Thank you for your help.
$(document).ready(function() {
$("#map").css({
height: 700,
width: 800
});
var myLatLng = new google.maps.LatLng(46.053791, -118.3131256);
MYMAP.init('#map', myLatLng, 11);
$("#showmarkers").ready(function(e){
MYMAP.placeMarkers('markers.xml');
});
});
var MYMAP = {
map: null,
bounds: null
}
MYMAP.init = function(selector, latLng, zoom) {
var myOptions = {
zoom:zoom,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
this.map = new google.maps.Map($(selector)[0], myOptions);
this.bounds = new google.maps.LatLngBounds();
}
MYMAP.placeMarkers = function(filename) {
$.get(filename, function(xml){
$(xml).find("marker").each(function(){
var name = $(this).find('name').text();
var address = $(this).find('address').text();
// create a new LatLng point for the marker
var lat = $(this).find('lat').text();
var lng = $(this).find('lng').text();
var point = new google.maps.LatLng(parseFloat(lat),parseFloat(lng));
// extend the bounds to include the new point
MYMAP.bounds.extend(point);
var marker = new google.maps.Marker({
position: point,
map: MYMAP.map
});
var infoWindow = new google.maps.InfoWindow();
var html='<strong>'+name+'</strong.><br />'+address;
google.maps.event.addListener(marker, 'mouseover', function() {
infoWindow.setContent(html);
infoWindow.open(MYMAP.map, marker);
});
<!-- *************** here is the code I need help with **************** -->
google.maps.event.addListener(marker, 'click', function() {
<!-- attempt 1 -->
<!--map.setZoom(10); -->
<!--map.setCenter(marker.getPosition());-->
<!--attempt 2 -->
<!--mapZoom = map.getZoom();-->
<!--startLocation = event.point; -->:
<!--attempt 3 (with and without MYMAP-->
<!--MYMAP.map.setZoom(10); -->
<!--MYMAP.map.panTo(marker.position); -->
});
google.maps.event.addListener(marker,'mouseout', function() {
infoWindow.close();
});
MYMAP.map.fitBounds(MYMAP.bounds);
});
});
}
I think the best way is to get the current zoom, increment it, and set the zoom to the new value, like this :
google.maps.event.addListener(marker, 'click', function() {
MYMAP.map.setZoom(MYMAP.map.getZoom()+1);
});
http://jsfiddle.net/OxyDesign/w26fL6f7/
Is it what you wanted ?
I am using google map api v3 with js and I am trying to to open infowndow on each marker on the map but through my code it is not opening here is my code sample please check it and tell me where is the error
<script type="text/javascript">
var map;
var markers = new Array();
function initialize() {
var map_center = new google.maps.LatLng(31.2330555556,72.3330555556);
var GPS = <%=GPS %>
var myOptions = {
zoom: 8,
scaleControl:true,
pancontrol: true,
streetViewControl: true,
center: map_center,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
mapTypeId: google.maps.MapTypeId.HYBRID
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var infowindow = new google.maps.InfoWindow();
for(i=0; i<GPS.length; i++)
{
var image = 'ico/no.png';
var ContentString = GPS[i].TITLE;
markers[i] = new google.maps.Marker(
{
position: GPS[i].GPS,
map: map,
draggable:true,
icon:image,
title:GPS[i].TITLE
});
google.maps.event.addListener(markers[i], 'click', function() {
infowindow.setContent(ContentString);
infowindow.open(map,markers[i]);
});
}
}
</script>
Try the following code:
google.maps.event.addListener(markers[i], 'click', function() {
infowindow.setContent(ContentString);
infowindow.open(map,this);
});
I have completed a program recently using the same api as yours. Facing to the same problem,I found the key factor is that the function of addlistener would work after the loop ended.It is said that the variable 'i' has reach to the maximizing value when the function of addlistener worked.So I have added a few steps to handle the problem. You can have a look at mine and I hope it is helpful for you.
function ShowParkingPoints() {
var adNum=document.getElementById("tableOne").rows.length;
var i;
var j;
var l;
var ly;
for (i=1;i<adNum;i++)
{
for(j=1;j<5;j++)
{
var k=i-1;
addArray[k]+=document.getElementById("tableOne").rows[i].cells[j].innerHTML;
}
}
for (i=0;i<adNum-1;i++){
var image = new sogou.maps.MarkerImage('images/flag.png',
new sogou.maps.Size(60, 60),
new sogou.maps.Point(0,0),
new sogou.maps.Point(0, 60));
var shape = {
coord: [1, 1, 1, 20, 18, 20, 18 , 1],
type: 'poly'
};
geocoder.geocode( { 'address': addArray[i]}, function(results, status) {
if (status == sogou.maps.GeocoderStatus.OK) {
var str=results[0].formatted_address;
//infowindow.setContent(str);
var marker1= new sogou.maps.Marker({
map: map,
icon: image,
shape: shape,
draggable:true,
position: results[0].geometry.location
});
i=i-1
markerArrayS[i]=marker1;
locationArray[i]=results[0].geometry.location;
sogou.maps.event.addListener(markerArrayS[i], 'click', function(event) {
makerClicked(event.latLng);
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
map.setCenter(mapCenter);
map.setZoom(13);
}
I think you just need to use 'i=i-1' to replace 'i' when you start to login event watcher.You can have a try. In a way,you need to notice that the order you storage in arrays when you want to read them out.