I have a function that loads my map to keep my map static.
<script>
var delArray = new Array();
var gm;
var map;
var iw;
var oms;
window.onload = function(){
gm = google.maps;
map = new gm.Map(document.getElementById('map_canvas'), {
mapTypeId: gm.MapTypeId.TERRAIN,
center: new gm.LatLng(-29.335205, 24.793563),
scrollwheel: false,
zoom: 6
});
iw = new gm.InfoWindow();
oms = new OverlappingMarkerSpiderfier(map,
{markersWontMove: true, markersWontHide: true});
}
</script>
I then use another function to construct my spiderfier data.
<script>
function spider(mapData){
var usualColor = 'eebb22';
var spiderfiedColor = 'ffee22';
var iconWithColor = function(color) {
return 'http://chart.googleapis.com/chart?chst=d_map_xpin_letter&chld=pin|+|' +
color + '|000000|ffff00';
}
var shadow = new gm.MarkerImage(
'https://www.google.com/intl/en_ALL/mapfiles/shadow50.png',
new gm.Size(37, 34), // size - for sprite clipping
new gm.Point(0, 0), // origin - ditto
new gm.Point(10, 34) // anchor - where to meet map location
);
oms.addListener('click', function(marker) {
iw.setContent(marker.desc);
iw.open(map, marker);
});
oms.addListener('spiderfy', function(markers) {
for(var i = 0; i < markers.length; i ++) {
markers[i].setIcon(iconWithColor(spiderfiedColor));
markers[i].setShadow(null);
}
iw.close();
});
oms.addListener('unspiderfy', function(markers) {
for(var i = 0; i < markers.length; i ++) {
markers[i].setIcon(iconWithColor(usualColor));
markers[i].setShadow(shadow);
}
});
var bounds = new gm.LatLngBounds();
for (var i = 0; i < mapData.length; i ++) {
var datum = mapData[i];
var loc = new gm.LatLng(datum[0], datum[1]);
bounds.extend(loc);
var marker = new gm.Marker({
position: loc,
title: datum[2],
animation: google.maps.Animation.DROP,
map: map,
icon: iconWithColor(usualColor),
shadow: shadow
});
marker.desc = datum[3];
oms.addMarker(marker);
delArray.push(marker);
}
map.fitBounds(bounds);
// for debugging/exploratory use in console
window.map = map;
window.oms = oms;
}
</script>
And Another to remove markers from the map:
<script>
function delMe(){
if(delArray){
for(i =0; i <= delArray.length; i++){
delArray[i].setMap(null);
}
this.delArray = new Array();
}
}
</script>
My map data (mapData) comes from a php script and passed on via Jason. And that's also where I call my delete function right before I call my spider (map) function. This I do to clear the map before I pass the new data.
$( document ).ready(function() {
delMe();
var pdata = $js_array;
spider(pdata);
});
Now, my problem is that all data is displaying perfectly but after calling the delMe() function it clears the markers 100% but then my map become unresponsive it's not loading new data when calling the spider() function with new data.
I can overcome this problem by reloading/creating the map again, but I want to avoid that and only use a static map. And if I don't delete markers it just fill the map with 100's of markers mixing the old and new.
I am a bit of a noob when it comes to javascript/jquery, any help will be much appreciated!.
It looks like you're missing an OMS removeMarker call in your delMe function, which should go something like this:
function delMe(){
if (delArray){
for (i =0; i <= delArray.length; i++){
oms.removeMarker(delArray[i]);
delArray[i].setMap(null);
}
this.delArray = [];
}
}
(It's possible you have other problems too, but here's a start).
It's not clear from what you write, but are you using the JS developer console? Google '[your browser] developer console' for more info — it lets you see if errors are causing your map to become unresponsive.
Related
I have the a situation where I want to limit the search results from a database that presents Google map markers on a map. Currently there are no criteria to limit this, however there could be sitautions where there are many markers and I want to contain this. I receive my markers in JSON - what would be the best practice to filter these to say 2km of the users current location?
My hunch is to do this with the actual JSON data on generation - but an idea of best practice here would be greatly appreciated as there isn't much in terms of guidance on SO.
Thanks!
Code presented below:
function showMarkers(str) {
if (str == "") {
document.getElementById("products").innerHTML = "";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//$('#mapMarkerPositions').html(this.responseText);
let data = JSON.parse(this.responseText);
merchantMarkers = [];
for (let i = 0; i < data.length; i++) {
merchantMarkers[i] = data[i];
}
resetMarker();
reloadMarkers();
}
}
xmlhttp.open("GET", "filterMarkers.php?s=" + str, true);
xmlhttp.send();
}
Then for the actual map:
<div id="merchantLocations">
<script>
var map;
var markers = [];
var merchantMarkers = [];
</script>
</div>
(additional code between this)
setMarkers(merchantMarkers);
var infowindow = new google.maps.InfoWindow({})
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(initialLocation);
});
}
}
function setMarkers(locations) {
var infowindow = new google.maps.InfoWindow({});
for (var i = 0; i < locations.length; i++) {
var merchant = locations[i];
var myLatLng = new google.maps.LatLng(merchant[1], merchant[2]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: icons.icon,
label: merchant[4]
});
/* ****************** */
map.panTo(myLatLng);
/* ****************** */
google.maps.event.addListener(
marker,
'click',
(function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker)
}
})(marker, i));
markers.push(marker);
}
}
function resetMarker() {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers = [];
}
function reloadMarkers() {
setMarkers(merchantMarkers);
}
Since you already have a set of markers with their locations (lat/lng) as well as the device's location using Geolocation, and you only want to put markers within a certain radius from the device origin, then what you can do is to compare the distance between the markers and the device location. You can use Distance Matrix API for this. The DM API can take in X no. of origin and destination in the form of address, latitude/longitude coordinates, or a place ID. So for example you have 1 origin (device's location) and multiple destinations (markers). This will provide you the distance results between your origin and each of your destinations. For example:
https://maps.googleapis.com/maps/api/distancematrix/json?origins=40.6655101,-73.89188969999998&destinations=40.6905615%2C-73.9976592%7C40.6905615%2C-73.9976592%7C40.6905615%2C-73.9976592%7C40.6905615%2C-73.9976592%7C40.6905615%2C-73.9976592%7C40.6905615%2C-73.9976592%7C40.659569%2C-73.933783%7C40.729029%2C-73.851524%7C40.6860072%2C-73.6334271%7C40.598566%2C-73.7527626%7C40.659569%2C-73.933783%7C40.729029%2C-73.851524%7C40.6860072%2C-73.6334271%7C40.598566%2C-73.7527626&key=YOUR_API_KEY
After getting the distance between them, you can then just add a simple if statement:
let result = JSON.parse(this.responseText);
//iterate through all the markers
for(i = 0 ; i <= no_of_markers ; i++ ){
//only show markers that are <= to 2km
if (result.rows[0].elements[i].distance.value <= 20000){
//Show Marker
}
}
Here is where you can learn more about Distance Matrix API. Note that you may also be billed for using this only if you went over the $200 free credit given per month. Here is the pricing sheet for your reference.
I have an increasingly complex Google map which plots thousands of points and clusters them. I have an infowindow opening when the user clicks one of the map markers and it all works great. However, one improvement I'd like to make is to force all other infowindows to close when a new one is opened so that only 1 infowindow can be open at once.
I've tried adding some code (if (infowindow) infowindow.close();) into the listener function to do this, but I think the issue is wider in that I'm currently creating an infowindow for each marker, and there is no access to other infowindows on the event which opens a new one. So, from reading around this it would seem to be a better idea to have just one infowindow which gets reused rather than many.
Trouble is, the code is at the edge of what I can really understand, and my experiments in doing this so far have just broken everything.
The code I currently have is as follows:
var _iconCenter = new google.maps.MarkerImage('/css/img/map-marker.png',
new google.maps.Size(38, 48),
new google.maps.Point(0,0),
new google.maps.Point(19, 44));
var shadow = new google.maps.MarkerImage('/css/img/map-marker-shadow.png',
new google.maps.Size(57, 49),
new google.maps.Point(0,0),
new google.maps.Point(7, 44));
var _icon = '/css/img/map-marker-purple.png';
var infowindow;
var markersArray = [];
var map;
var currentPosition = 0;
var currentmarker;
var firstload = true;
var maploaded = false;
var interval = 5000;
var geocoder;
var stylez = [];
function initialize(items,loop,zoom) {
geocoder = new google.maps.Geocoder();
if (items.length > 0) {
var latlng = new google.maps.LatLng(items[0].Lat, items[0].Lng);
var myOptions = {
zoom: zoom,
center: latlng,
//mapTypeControl: false,
streetViewControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), myOptions);
map.setOptions({styles: stylez});
for (var i = 0; i < items.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(items[i].Lat, items[i].Lng),
title: items[i].Title,
icon: _icon,
shadow: shadow,
infocontent: items[i].Description
});
marker.setMap(map);
attachListener(marker,'marker:'+i);
markersArray.push(marker);
}
//set style options for marker clusters (these are the default styles)
mcOptions = {
gridSize: 44
}
var markerCluster = new MarkerClusterer(map, markersArray, mcOptions);
google.maps.event.addListener(map, "tilesloaded", function () {
if(loop == true){
SetLoop();
}
});
function attachListener(marker,content){
google.maps.event.addListener(marker, "click", function () {
var infowindow = new google.maps.InfoWindow();
map.setCenter(new google.maps.LatLng(marker.getPosition().lat(), marker.getPosition().lng()));
infowindow.setContent(content);
infowindow.open(map,this);
});
}
}
}
function SetLoop() {
//This will fire everytime map loads or recenteres
maploaded = true;
if (firstload) {
firstload = false;
Recenter();
}
}
function Recenter() {
//If previous iteration is not loaded completely, wait to avoid errors
//It could happen for slow internet connection
if (maploaded) {
maploaded = false;
} else {
//keep adding 1 second to interval for slow connection till page loads
interval = interval + 1;
setTimeout("Recenter()", interval);
return;
}
if (infowindow != null && currentmarker != null) {
//currentmarker.icon = _icon;
currentmarker.icon = _iconCenter;
currentmarker.setMap(map);
infowindow.close(map, currentmarker);
}
markersArray[currentPosition].icon = _iconCenter;
markersArray[currentPosition].setMap(map);
map.setCenter(new google.maps.LatLng(markersArray[currentPosition].getPosition().lat(), markersArray[currentPosition].getPosition().lng()));
infowindow = new google.maps.InfoWindow({
content: markersArray[currentPosition].infocontent,
size: new google.maps.Size(50, 50)
});
infowindow.open(map, markersArray[currentPosition]);
currentmarker = markersArray[currentPosition];
if (currentPosition >= markersArray.length - 1) {
currentPosition = 0;
} else {
currentPosition++;
}
if (markersArray.length > 1) {
setTimeout("Recenter()", interval);
}
}
Is the best way to re-use the infowindow or is it okay to do this another way? Any help in pointing me in the right direction here would be much appreciated, thanks folks!
Remove the 'var infowindow' declaration from function attachListener(). If you declare it inside the function it becomes local to the function and you create a new instance each time you execute the function. so:
function attachListener(marker,content){
google.maps.event.addListener(marker, "click", function () {
// marker.getPosition() already returns a google.maps.LatLng() object
map.setCenter(marker.getPosition());
infowindow.close();
infowindow.setContent(content);
infowindow.open(map,this);
});
}
and instead, declare it as a global variable:
var _icon = '/css/img/map-marker-purple.png';
var infowindow = new google.maps.InfoWindow();
//...etc
so that you have only one infowindow object in the whole application
I have a mysql table with a series of lat/lng points being written to an xml file and imported to google maps as points. This seems to be working fine, but rather than simply marking them with a point I'd like to generate a polyline between each of them. In looking at the developer docs, I noticed that the example iterates through creating a new latlng object for each line/ set of points. Is there a way I can dynamically call a series of points to generate multiple lines from my database? Sorry if this seems like an obvious fix- I'm a bit new to the maps api. Thanks in advance!
The output XML file I'm using looks something like this:
Location name="2012-04-01 12:28:18" lat="42.9523010667" lon="-78.8189444333"/
Location name="2012-04-01 12:28:06" lat="42.95219345" lon="-78.81931905"/
Location name="2012-04-01 12:27:54" lat="42.9522356" lon="-78.8192848667"/..... etc
HTML/ Script Calling the XML coords into the map:
function load() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(42.9521, -78.8198), 20);
GDownloadUrl("gmaps_genxml2.php", function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("Location");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("timestamp");
var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lon")));
var marker = createMarker(point, name);
map.addOverlay(marker);
}
});
Code snippet in question on developers.google doc:
var flightPlanCoordinates = [
new google.maps.LatLng(37.772323, -122.214897),
new google.maps.LatLng(21.291982, -157.821856),
new google.maps.LatLng(-18.142599, 178.431),
new google.maps.LatLng(-27.46758, 153.027892)];
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2});
flightPath.setMap(map);}}}
function createMarker(point, name) {
var marker = new GMarker(point, customIcons[type]);
var html = "<b>" + name;
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml(html);
});
return marker;
}
I'm currently not showing any errors in the console. This is how I've attempted to implement the two previous code snippets from the original post, but I'm not getting the map to display any lines/ points. Might it be the way I'm defining the point variable/ it is not storing the array, but a single point?? I've tried using [] in defining "point" as well- but this didn't work/ didn't show any errors either...
function load() {
if (GBrowserIsCompatible()) {
// Create an instance of Google map
var map = new GMap2(document.getElementById("map"));
// Tell the map where to start
map.setCenter(new GLatLng(42.9521, -78.8198), 20);
GDownloadUrl("gmaps_genxml2.php", function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("Location");
for (var i = 0; i < markers.length; i++) {
var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lon")));
var polyline = new GPolyline(point, '#ff0000', 5, 0.7);
map.addOverlay(polyline);
}
});
}}
Got it!
Here I was asking the internet, and the kid sitting behind me knew the whole time...
I was setting up the array incorrectly. To solve the problem:
----create an empty array
----use '.push' to insert into array
function load() {
if (GBrowserIsCompatible()) {
// Create an instance of Google map
var map = new GMap2(document.getElementById("map"));
// Tell the map where to start
map.setCenter(new GLatLng(42.9521, -78.8198), 20);
GDownloadUrl("gmaps_genxml2.php", function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("Location");
var points = [];
for (var i = 0; i < markers.length; i++) {
points.push(new GLatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lon"))));
}
var polyline = new GPolyline(points, '#ff0000', 5, 0.7);
map.addOverlay(polyline);
});
}}
Im doing a php web, that refresh its content with ajax and map is refreshed calling with a timer the load() function of the map.. thats no problem
My problem is, i have to put a map.setCenter first time. Imagine i start to search a marker i put in the map, and then after 20 seconds it reloads the map and it is going again to my "setCenter".. i dont want that. I want to refresh but the map STAYS where i am searching...
is there any function for doing that? here is my load function
function load() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(-34.603365,-58.379416),11);
map.enableScrollWheelZoom();
GDownloadUrl("creoXml.php", function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("numMovil");
var type = "Movil";
var nameTit = "Móvil "+name;
var point = new GLatLng(parseFloat(markers[i].getAttribute("latitud")),
parseFloat(markers[i].getAttribute("longitud")));
var marker = createMarker(point, nameTit,type);
map.addOverlay(marker);
}
});
}
}
function createMarker(point, name,type) {
var marker = new GMarker(point, customIcons[type]);
var html = "<b>" + name + "</b>";
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml(html);
});
return marker;
}
look that everytime i call load(), my setCenter is that.. and if i remove the setCenter with a condition, the map turns into white.. thanks
Put a global variable in you code and call it loading=1.Then in your load function put something like this
if(loading==1){
setCenter....
loading=0;
}
I've got this problem when removing a Marker from an array. I click on the map and place markers where i have clicked, the markers are then saved in an array. When removing them it only works in the order i have placed them but backwards, that means i place 1 2 3 but have to remove them like 3 2 1.
If i try to remove the markers in random order, the first one is removed, but then the others just stop working, the listener still works, but it seems like the forloop doesnt find the other markers in the array.
Any ideas? I'm completely lost.
Here is the code:
var map;
var tempLatLng;
var zoomLevel;
var markers = [];
var zoomLevels = [];
var count = -1;
var nullLatlng = new google.maps.LatLng(84.52,45.16);
var nullMarker = new google.maps.Marker({
position: nullLatLng,
});
function initialize() {
var myLatlng = new google.maps.LatLng(55.605629745598904,13.000441789627075);
var myOptions = {
zoom: 17,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel:false
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
//Puts a listener on the map, when clicking on the map, it places a marker.
google.maps.event.addListener(map, 'click', function(event) {
zoomLevel = map.getZoom();
document.getElementById("zoom").value = zoomLevel;
tempLatLng = event.latLng;
setTimeout("placeMarker(tempLatLng)", 800); //placeMarker is called with a duration so that //doubleclicking doesn't bother the placement.
});
}
//Function to place markers.
function placeMarker(location) {
if(zoomLevel == map.getZoom()){
if(true){
var marker1 = new google.maps.Marker({
position: location,
map: map,
draggable:true
});
count = count + 1;
markers[count] = marker1;
document.getElementById("count").value = count;
google.maps.event.addListener(marker1,'rightclick', function(event){
document.getElementById("test2").value = "funkar";
for(var i = 0 ;i < markers.length ;i++){
if(markers[i].getTitle() == marker1.getTitle()){
marker1.setMap(null);
document.getElementById("markerpos").value = markers[i].getTitle();
document.getElementById("test1").value = markers[i].getTitle();
count = count - 1;
document.getElementById("count").value = count;
markers[i] = nullMarker;
}
}
});
marker1.setTitle(location.toString());
}
map.setCenter(location);
}
}
Here is the JSFiddle Demo:
Basically, you were using var count to keep track of the number of markers. You can do markers.length for that. Instead of using markers[count] you can use native array's push method to add element into the array. To remove use splice(i, 1); where i is the element's position and remove 1 element from that position. Also, to check if two markers are equal or the "same" instead using getTitle() use === which does:
is exactly equal to (value and type)
The problem is if you create two or more markers on the same position it would remove both markers but in reality you only remove one of the two "clones" and thus leaving a marker un-removable. This is caused by using getTitle which returns lat lng and if you have two markers w/ same lat lng you have an issue. Also, i changed, within your onclick function, marker1 to this which are referring to the same object for readability.
//Function to place markers.
function placeMarker(location) {
if (zoomLevel == map.getZoom()) {
if (true) {
var marker1 = new google.maps.Marker({
position: location,
map: map,
draggable: true
});
count = count + 1;
markers.push(marker1);
document.getElementById("count").value = markers.length;
google.maps.event.addListener(marker1, 'rightclick', function(event) {
document.getElementById("test2").value = "funkar";
for (var i = 0; i < markers.length; i++) {
if (markers[i] === this) {
this.setMap(null);
document.getElementById("markerpos").value = markers[i].getTitle();
document.getElementById("test1").value = markers[i].getTitle();
markers.splice(i, 1);
document.getElementById("count").value = markers.length;
}
}
});
marker1.setTitle(location.toString());
}
map.setCenter(location);
}
}