This question is the "episode 2" of this: Original question
Hi !
I'm still having trouble with my map. In fact, I believed the solution in the link above had solve my problem, but I figured out another problem.
My code and my aim are almost the same as the "episode 1" of this question.
As a reminder, I have a Leaflet map that uses MarkerCluster to show ~36.000 markers. Each marker must have a Popup (that appear onclick) which contains many informations.
As they were too many informations to get at one time (I mean to get all points and all informations at one time), I had the idea to get latitude, longitude and a single ID in order to show the Markers on the map. Next, when click on a Popup, the script make an Ajax request to get infos from a Database, using the single ID contains by each marker.
For now, and with the great help of maximkou, I can make this happen. My problem is, that only the last ID is consider, so it always request on the same ID and always show the same information (which is not what I try to do).
I tried many things (like getting all the markers on the map, trying to put markers on an array, etc.) but I can't figure out how to get this work.
I don't think it's impossible (but maybe it is), I think I simply lack skill on Javascript.
If you have another solution or idea, I will be glad to test it to !
I will now show you an extract of my current code:
function makeMap(pointsToInsert){
if (typeof map != 'undefined') {
map.off();
map.remove();
}
var tiles=L.tileLayer('https://api.mapbox.com/styles/v1/mapbox/streets-v9/tiles/256/{z}/{x}/{y}?access_token=', {
attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © Mapbox',
maxZoom: 20,
}),
latlng = L.latLng(48.8557, 2.3600);
var map = L.map('map', {center: latlng, zoom: 9, zoomControl:false, layers: [tiles]});
var arr = JSON.parse(pointsToInsert); //pointsToInsert come from a PHP script call before
var markers = L.markerClusterGroup();
for (var i = 0; i < arr.length; i++) {
var a = arr[i];
var ID = a[0];
var lat = a[1];
var lon = a[2];
var marker = L.marker(new L.LatLng(lat, lon));
marker.bindPopup(ID);
markers.addLayer(marker);
marker.on('click', function () {
var datas = marker.getPopup().getContent();
var popup = L.popup()
.setLatLng(this.getLatLng())
.setContent("Loading ...")
.openOn(map);
$.ajax({
url: 'getInfos.php',
type : 'POST',
data : "id=" + datas,
dataType: 'html',
success: function (data) {
popup.setContent(data);
},
error : function(resultat, statut, erreur){
alert("Error");
},
});
});
}
map.addLayer(markers);
}
I need some help here, please
If you want me to be more specific or to add others extract just let me know !
Thanks in advance
Related
At the moment I'm working on a project in which I'm supposed to show various customers worldwide on a map. I determine the coordinates of these customers using the Bing Maps API. But if I then want to display these customers on the map, I get the error for some that the coordinates are wrong. The coordinates in the database look correct and are returned to me by the Bing Maps API.
Now to the question:
How do I catch this error so that the script doesn't crash because of it?
let map;
let searchManager;
let customers = <?= json_encode($elements); ?>;
let pins = [];
let iconURL = '';
function GetMap() {
var statusDropdownValue = parseInt($('#status').val());
map = new Microsoft.Maps.Map('#map', {
zoom: 1
});
$.each(customers, function(index, value) {
var customerLocation = new Microsoft.Maps.Location(value['latitude'], value['longitude']);
var pin = new Microsoft.Maps.Pushpin(customerLocation, {
icon: baseURL + 'assets/images/pin.png'
});
pin.metadata = {
id: value['id'],
customerName: value['customer_name'],
postCode: value['post_code'],
city: value['city'],
countryCode: value['country_code']
};
pins.push(pin);
});
Microsoft.Maps.loadModule("Microsoft.Maps.Clustering", function () {
clusterLayer = new Microsoft.Maps.ClusterLayer(pins);
map.layers.insert(clusterLayer);
});
Microsoft.Maps.loadModule('Microsoft.Maps.AutoSuggest', function () {
var manager = new Microsoft.Maps.AutosuggestManager({ map: map });
manager.attachAutosuggest('#search', '#search-container-search-bar', selectedSuggestion);
});
}
Error:
Uncaught Error: Invalid latitude
n https://r.bing.com/rp/iKR9c24bDSIz79-enVSnBoJvZx8.br.js:1
GetMap http://localhost/projects/BattermannTillery_HK_Locator/maps:101
each jQuery
GetMap http://localhost/projects/BattermannTillery_HK_Locator/maps:100
notifyMapReadyForBootstrap https://www.bing.com/api/maps/mapcontrol?callback=GetMap&setMkt=en-US&setLang=en&key=AlV57vXOvuSENqgwu6hnNKGhiLf85dbTMlnDY81z2cGq40L1xkMdXUVSkEhvqfvv:12
<anonymous> https://r.bing.com/rp/RENSVX2edu6CiHiu-aMi-GbtqbA.br.js:1
<anonymous> https://r.bing.com/rp/RENSVX2edu6CiHiu-aMi-GbtqbA.br.js:1
I would do the following to debug this issue:
Open dev console in browser, add a break point where you create the Location object. Check to see if value['latitude'] is a string number or an actual number ("1" vs 1). If it is a string, wrap value['latitude'], value['longitude'] with parseFloat like (parseFloat(value['latitude']). This is the most common cause of this type of error.
If the above doesn't solve your issue, it would be best to check your data (I'm assuming you have the coordinates stored somewhere). Double check you haven't reversed latitude and longitude values (take a couple of entries and manually search for them on bing.com/maps and check the coordinates to verify what you have in your lat/lon columns is in the same general area). If you can query your dataset (is it a database?), you can check all latitude and longitude values. Latitude values should be between -90 and 90 degrees, and longitude between -180 and 180. If you find anything outside of this range it will be either due to bad data, or you have latitude/longitude values swapped in your data.
I am currently working on a web application where I'm trying to display a heat map using the library called Leaflet.heat. It works with the Leaflet Javascript library to create an overlay heat map that looks pretty good. I feel like I'm pretty much there but having one last bit of trouble with array format and can't figure out what is wrong. Let me share the code that I have right now.
var mymap;
var marker = [];
var heatMapArr = [];
window.onload = function() {
alert("in initial func");
uponPageLoadDefault();
};
function uponPageLoadDefault()
{
//initial default page load
var branches = new L.LayerGroup();
var items = JSON.parse('${branches}');
var j = 0;
for(var i = 0; i < items.length; i++)
{
var LamMarker = new L.marker([items[i].lat, items[i].lon]);
//GOT RID OF FUNCTION CALL.
var heatMapPoint = {
lat: items[i].lat,
lon: items[i].lon,
intensity: items[i].tranCount
};
heatMapArr.push(heatMapPoint);
LamMarker.bindPopup("<b>" + items[i].branchName + "</b><br>" + items[i].branchAdd + "</br><br>" + items[i].branchCity + "</br><br>" + items[i].branchSt + "</br><br>" + items[i].branchZip + "</br><br>TranCount: " + items[i].tranCount).addTo(branches);
marker.push(LamMarker);
}
mbAttr = 'Map data © OpenStreetMap contributors, ' +
'CC-BY-SA, ' +
'Imagery © Mapbox',
mbUrl = 'https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoidGFzdHlicm93bmllcyIsImEiOiJjaXgzZWxkaHowMWZhMnlvd2wzNHllaGwxIn0.0RSZEhtR0OBLMbwjqFfBkg';
var outdoors = L.tileLayer(mbUrl, {id: 'mapbox.outdoors', attribution: mbAttr});
var heatmap = L.heatLayer(heatMapArr, {radius: 6, blur: 8,maxZoom: 8});
var map = L.map('map', {
center: [39.73, -104.99],
zoom: 10,
layers: [outdoors, branches, heatmap]
});
var baseLayers = {
"Outdoors": outdoors
};
var overlays = {
"Branches": branches,
"HeatMap": heatmap
};
L.control.layers(baseLayers, overlays).addTo(map);
So basically I am trying to use the heat map display as a possible overlay that the user can select. The Leaflet-heat library tutorial is located at https://github.com/Leaflet/Leaflet.heat/ and it explains what needs to be done in order for the library to work.
Anyway, I have a list of items with latitude, longitude, and intensity amount, so I'm trying to use that, its called items. I iterate through that, pushing the select information into my heat map array. At this point I should be almost all set besides adding the overlays and creating the map. When I run the program, the map displays but the overlay icon is absent so there is an issue.
In the website tutorial they use a separate Javascript file which has an array of objects to create their heat map. I tried this with my program and then everything worked, which quickly led me to believe there's a problem with my array of objects, probably some minor formatting thing.......I am using another function to create an object with the data I have, so it will be in the same format as the website example.
I tried to use alert and other statements and compare my array to theirs but it hasn't yielded anything useful so I wanted to post my issue here on Stack to get some feedback from others on what could be wrong. I think its something really small that I may not be seeing.
Any feed back is greatly appreciated and certainly let me know if there's any questions.
Thanks!
This question already has answers here:
How to set zoom level in google map
(6 answers)
Closed 6 years ago.
I have been trying for 4+ years to figure out how to use google maps. Im beyond ecstatic to have finally become able to generate a map wiht the correct address.
This is my javascript.
I'm now struggling with how to set the zoom level. I've tried it in each of the places I've shown below - but none of them work. In each case (regardless of the number I set as the zoom level) I get a really close up map of the specific building.
Can anyone see what I'm doing wrong, or what I need to do in order to get my map to recognise my request for a zoom level? I don't get any js errors showing in the console.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 5
});
var bounds = new google.maps.LatLngBounds();
// var opts = {
// zoom: 10,
// max_zoom: 16
// }
var n = addresses.length;
for (var i = 0; i < n; i++) {
var lat = addresses[i].latitude;
var lng = addresses[i].longitude;
if (lat == null || lng ==null){
console.log(addresses[i].name + " doesn't have coordinates");
}else {
var address = new google.maps.Marker({
position: {lat: parseFloat(lat), lng: parseFloat(lng)},
title: addresses[i].name,
map: map //,
// zoom: 8
});
bounds.extend(address.position);
}
}
map.fitBounds(bounds);
}
Note in response to why this question is different to many others asked on SO. I am specifically struggling with how and where to use the features provided in this JS. I can't understand any of the JS I have managed to generate - the version above is the result of 4+ years of effort in trying to learn. I can't take generic ideas in other posts and apply them as easily as others may be capable of doing. Please bear with me as I try to learn to decipher how to communicate with these languages. It's not something that I've been able to grasp readily.
Also, and specifically to the point in the answer you have flagged - maybe the code was good at the point in time the question was asked, but it looks from the google library that the correct expression should be "zoom:4" not setZoom(something). I tried both and can't get either of them to work in my code.
XOMENA'S SUGGESTION
Taking Xomena's suggestion, I tried to define zoom and center in my map function (although I'm not suer if I've done this in the correct place).
This doesnt work. The console shows an error with my js file that says:
Uncaught SyntaxError: Unexpected identifier
Now, my js file has:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
setZoom: 5
setCenter = addresses.first
});
var bounds = new google.maps.LatLngBounds();
// var opts = {
// zoom: 10,
// max_zoom: 16
// }
var n = addresses.length;
for (var i = 0; i < n; i++) {
var lat = addresses[i].latitude;
var lng = addresses[i].longitude;
if (lat == null || lng ==null){
console.log(addresses[i].name + " doesn't have coordinates");
}else {
var address = new google.maps.Marker({
position: {lat: parseFloat(lat), lng: parseFloat(lng)},
title: addresses[i].name,
map: map //,
// zoom: 8
});
// bounds.extend(address.position);
}
}
// map.fitBounds(bounds);
}
I can't find an example of how to set this up to work. I've tried putting the set zoom and set centre lines in each block of text in this js file, but I can't find a formulation that works.
NEXT ATTEMPT
I tried moving my application javascript include tag out of the head tag and beneath the body tags on my application.html.erb.
Now, I have an error that says:
js?key=AIzaSyAleQgfNH3HRQVUCYnyAzp46xmXW7WrWrc&callback=initMap:95 Uncaught Eb {message: "initMap is not a function", name: "InvalidValueError", stack: "Error↵ at new Eb (https://maps.googleapis.com/m…3HRQVUCYnyAzp46xmXW7WrWrc&callback=initMap:130:73"}message: "initMap is not a function"name: "InvalidValueError"stack: "Error↵ at new Eb (https://maps.googleapis.com/maps/api/js?key=AIzaSyAleQgfNH3HRQVUCYnyAzp46xmXW7WrWrc&callback=initMap:41:365)↵ at Object._.Fb (https://maps.googleapis.com/maps/api/js?key=AIzaSyAleQgfNH3HRQVUCYnyAzp46xmXW7WrWrc&callback=initMap:41:475)↵ at Lg (https://maps.googleapis.com/maps/api/js?key=AIzaSyAleQgfNH3HRQVUCYnyAzp46xmXW7WrWrc&callback=initMap:95:420)↵ at https://maps.googleapis.com/maps/api/js?key=AIzaSyAleQgfNH3HRQVUCYnyAzp46xmXW7WrWrc&callback=initMap:130:58↵ at Object.google.maps.Load (https://maps.googleapis.com/maps/api/js?key=AIzaSyAleQgfNH3HRQVUCYnyAzp46xmXW7WrWrc&callback=initMap:21:5)↵ at https://maps.googleapis.com/maps/api/js?key=AIzaSyAleQgfNH3HRQVUCYnyAzp46xmXW7WrWrc&callback=initMap:129:20↵ at https://maps.googleapis.com/maps/api/js?key=AIzaSyAleQgfNH3HRQVUCYnyAzp46xmXW7WrWrc&callback=initMap:130:73"__proto__: ErrorLg # js?key=AIzaSyAleQgfNH3HRQVUCYnyAzp46xmXW7WrWrc&callback=initMap:95(anonymous function) # js?key=AIzaSyAleQgfNH3HRQVUCYnyAzp46xmXW7WrWrc&callback=initMap:130google.maps.Load # js?key=AIzaSyAleQgfNH3HRQVUCYnyAzp46xmXW7WrWrc&callback=initMap:21(anonymous function) # js?key=AIzaSyAleQgfNH3HRQVUCYnyAzp46xmXW7WrWrc&callback=initMap:129(anonymous function) # js?key=AIzaSyAleQgfNH3HRQVUCYnyAzp46xmXW7WrWrc&callback=initMap:130
kwift.CHROME.min.js:1271 Uncaught SyntaxError: Identifier 'findGoodContent' has already been declared
I have seen SO posts form others using angular (i don't use that) which suggest adding another js file to the view where the map is displayed.
Can anyone help solve this for rails where angular is not used?
The map.fitBounds() method adjusts the zoom level automatically to show all locations that you added into LatLngBounds. If you want to set zoom level yourself, don't use map.fitBounds() and use map.setZoom() method instead.
https://developers.google.com/maps/documentation/javascript/reference#Map
i hope you can help me with my following problem. since days I´m tinkering on it, but it won´t run...
I´m writing a little web-app based on Google Maps API on wich i can mark my actual position on a map with a modified marker-symbol an so on. Everything works great so far. I receive my geolocation via HTML5-Geolocation function and write the values in to a mysql database. In a separate function (see below) i read out this data an set the marker with my modified symbol on the map.
The next I wan´t to solve is to remove the marker after about 40 minutes automatically from the map. For this I created a separate table on my database which gets filled with the marker-information from the main table. This works so far, I solved it with a php-script and a cron-job. Then the entry from the main table becomes deleted. What makes me insane is to remove the marker after the 40 minutes from the map. I tried several things, from creating arrays with the data of the "to-remove-table", i played around with the setMap-function of Google Maps API, but I´m still on the line.
Here is my code where I read out the data from database and set the marker on the map:
function markPolitesse() {
var infoWindow_spotted = new google.maps.InfoWindow;
downloadUrl("phpsqlajax_genxml2.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("politesse_spotted");
for (var i = 0; i < markers.length; i++) {
var number = markers[i].getAttribute("number");
var city = markers[i].getAttribute("city");
var zipcode = markers[i].getAttribute("zipcode");
var street = markers[i].getAttribute("street");
var type = markers[i].getAttribute("street");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + city + "</b> <br/>" + zipcode + "</b> <br/>" + type + "</b> <br/>";
var marker = new google.maps.Marker({
map: map,
position: point,
title: number,
icon: politessenImage
});
bindInfoWindow(marker, map, infoWindow_spotted, html);
}
});
}
The main- and the "remove-table" contain the following fields:
number, city, zipcode, street, streetnumber, coordinates_lat, coordinates_lng, time, date
I hope you have a impulse for me I would be thankful...
Regards,
Stefan
Store the marker in a global variable/outside the function, then in your function do the following:
marker.setMap(null);
// set up new marker
Then assign your new marker.
I was trying to follow this example http://code.google.com/p/gmaps-samples/source/browse/trunk/fusiontables/custom_markers.html?spec=svn2515&r=2515, to create custom markers.
I tried to change the example to use my data. The difference is that my data is already geocoded. I had trouble trying to figure why it didnt work when I changed the table id and the columns on the code.
So i printed the 'Address' on the original code and the one with my data.
The original code with the sample fusion-table, outputs the location like this
(37.4471132, -122.1602044)
Because my table is already geocoded I took away most of the function
function codeAddress(row) {
alert(row[1]);
var marker = new google.maps.Marker(
{
map : map,
position : row[1],
//this is where the magic happens!
icon : new google.maps.MarkerImage(icon: new google.maps.MarkerImage("http://www.google.com/images/icons/product/fusion_tables-32.png")
});
}
But the alert only diplays the coordinate a little bit different
<Point><coordinates>-78.423652,-0.203057,0.0</coordinates></Point>
So yeah, that is what I think it is not working
My opinion is that position : has to be followed by a google.maps.LatLng.
It looks like the row data is from KML, you need to extract the first two numbers to create the LatLng.
Mia DiLorenzo is right, the MarkerOption position expects a LatLng object.
Look at this example, which is very similar to yours, but it uses the Coordinates field to create the marker.
The example assumes, that the data in the Coordinates field is comma-separated "lat,lng"
e.g. 47.7672,-3.2022
But if your data happens to be in KML format then you can just extract the lat/lng values. The values are in order: longitude, latitude, and altitude (see the KML reference for details about KML coordinates):
function createLatLngObject(kmlString) {
//remove XML tags from input
var xmlRegEx = /<\/?\w+>/;
var kmlValue = kmlString.replace(xmlRegEx,'');
// now kmlValue contains e.g. -78.423652,-0.203057,0.0
//extract latitude and longitude
var coordinates = kmlValue.split(",");
var lat = coordinates[1];
var lng = coordinates[0];
return new google.maps.LatLng(lat, lng);
}
function createMarker(row) {
var latlng = createLatLngObject(row[1]);
var marker = new google.maps.Marker({
map: map,
position: latlng,
icon: new google.maps.MarkerImage("http://www.google.com/images/icons/product/fusion_tables-32.png")
});
}