I'm having a bit of trouble trying to loop out multiple markers onto a map using information stored in an array.
The code creates the map no problem, but it's not displaying the markers I'm trying to loop out...
As you can see from the code below, there are two functions that are creating markers. The first is simply using two values. This marker displays fine.
The second function however, is grabbing the data from an array (the array has been set up to "squish" the latitude and longitude data together, in that order, as Google Maps requires it to be) and does not display anything when run.
Any ideas? I'm stumped!
Thanks in advance!
Here's the code:
Initial "locations" array:
var locations = new Array();
for (var i = 0; i < data.length; i++)
{
var row = data[i];
var longitude = row[0];
var latitude = row[1];
locations[i] = latitude + longitude;
}
callMap(locations, locationFilename, userLatitude, userLongitude);
Google Maps Functions
function callMap(locations, locationFilename, userLatitude, userLongitude) {
var mapOptions = {
zoom:16,
center: new google.maps.LatLng(userLatitude, userLongitude),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('mapView'),mapOptions);
setMarkers(map, locations, locationFilename);
currentPosition(map, userLatitude, userLongitude);
}
function currentPosition(map, userLatitude, userLongitude)
{
var userLatLng = new google.maps.LatLng(userLatitude, userLongitude);
var marker = new google.maps.Marker({
position: userLatLng,
map: map
});
}
function setMarkers(map, locations, locationFilename) {
for (var i = 0; i < locations.length; i++) {
var markerLatLng = new google.maps.LatLng(locations[i]);
var marker = new google.maps.Marker({
position: markerLatLng,
map: map
});
}
}
A google.maps.LatLng takes two numbers for arguments.
This is not correct:
var markerLatLng = new google.maps.LatLng(locations[i]);
This should work:
for (var i = 0; i < data.length; i++)
{
var row = data[i];
var longitude = row[0];
var latitude = row[1];
locations[i] = new google.maps.LatLng(latitude,longitude);
}
Then
function setMarkers(map, locations, locationFilename) {
for (var i = 0; i < locations.length; i++) {
var markerLatLng = locations[i];
var marker = new google.maps.Marker({
position: markerLatLng,
map: map
});
}
}
}
You're just adding strings together, it needs to be an array:
for (var i = 0; i < data.length; i++) {
var row = data[i];
var longitude = row[0];
var latitude = row[1];
locations[i] = [latitude, longitude];
}
var markerLatLng = new google.maps.LatLng(locations[i].join(','));
Related
Hi everyine please help me, I am trying to do a search filter on my vehicle tracking, the flow is, the servlet queries all data when there is no parameter filter is being sent by ajax. for example, I do have 5 data on query result so there will be 5 markers on the map, the ajax runs every two seconds so when I request a parameter for example only this spesific vehicle would be shown the query result would only be one, supposedly only marker on the screen, but the previous markers are not vanishing and keep up on the screen. how can I reset the markers into 0? can anyone please help me thanks! here is my code
<script type="text/javascript">
var values = [];
var map;
var markers = [];
function initMap()
{
var options = {
center: {lat: -33.890542, lng: 151.274856},
zoom: 4
};
map = new google.maps.Map(document.getElementById('map'), options);
var count = 0;
setInterval(function() {
getGps();
for(var i = 0; i <= markers.length; i++){
markers[i].setPosition(new google.maps.LatLng(values[count][1],values[count][2]));
count++;
}
}, 2000);
}
function removeMarkers(){
for(var i=0; i<markers.length; i++){
markers[i].setMap(null);
}
markers=[];
}
function getGps() {
xmlhttp.onreadystatechange=function() {
if( xmlhttp.readyState==4 && xmlhttp.status==200 ) {
removeMarkers();
var res = xmlhttp.responseText;
console.log(res);
var split1 = res.split("|");
if(split1[0] != "NOK"){
for(var i = 0; i < split1.length; i++){
var split2 = split1[i].split(",");
String(split2);
var holder1 = holder = [split2[0],split2[1],split2[2]];
values.push(holder1);;
var marker1 = marker = new google.maps.Marker({map: map, icon: 'images/mapvehicle.png', draggable: true});
markers.push(marker1);
}
}
}
};
xmlhttp.open("POST","GpsPost",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("txtTerminal="+document.getElementById('txtTerminal').value+"&txtMerchant="+document.getElementById('txtMerchant').value+"&txtAccount="+document.getElementById('txtAccount').value);
}
add this function and call it after this line .
if( xmlhttp.readyState==4 && xmlhttp.status==200 ) {
function removeMarkers(){
for(i=0; i<markers.length; i++){
markers[i].setMap(null);
}
markers=[]
values=[]
}
I will start by saying that I am relatively new to JS, so please forgive my ignorance if this is obvious.
I am trying to add markers to a google map. I have created an array coordList, then used the geocoding api to get the lag and long from the addresses and pushed them into coordList.
I am now trying to use the coordList array to plot markers on the map, however I cannot seem to get the values from the coordList array. When I run console.log(typeof coordList) - it tells me it's an object, but when i look at the array with console.log(coordList) it just looks like a normal array?
var coordList = [];
var address = [];
address.push('52+Kalynda+pde,+bohle+plains,+QLD')
address.push('51+Frank+St,+Kirwan+QLD+4817');
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: new google.maps.LatLng(-19.259854,146.8001348),
mapTypeId: 'roadmap'
});
}
function getLatLong(address){
var index;
for (index = 0; index < address.length; ++index) {
var request = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + address[index] + '&key=[MY_key]';
$.getJSON( request, function( data ) {
var lat = data.results[0].geometry.location.lat;
var lng = data.results[0].geometry.location.lng;
var coords = [];
coords.push(lat);
coords.push(lng);
//push coords into coordList
coordList.push(coords);
});
}
}
// Loop through the results array and place a marker for each
// set of coordinates.
function addMarkers(coordList) {
for (var i = 0; i < coordList.length; i++) {
var coords = coordList[i];
var latLng = new google.maps.LatLng(coords[0],coords[1]);
var marker = new google.maps.Marker({
position: latLng,
map: map
});
}
}
getLatLong(address);
addMarkers(coordList);
Your problem is that $.getJSON() is an asynchronous request and your code executes addMarkers() before than $.getJSON() finishes, so coordList is empty.
You can add the markers inside $.getJSON() callback. For example:
var address = [];
address.push('52+Kalynda+pde,+bohle+plains,+QLD')
address.push('51+Frank+St,+Kirwan+QLD+4817');
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: new google.maps.LatLng(-19.259854,146.8001348),
mapTypeId: 'roadmap'
});
}
function getLatLongAndAddMarkers(address){
var index;
for (index = 0; index < address.length; ++index) {
var request = 'https://maps.googleapis.com/maps/api/geocode/json?dress=' + address[index] + '&key=[MY_key]';
$.getJSON( request, function( data ) {
var latLong = new google.maps.LatLng(data.results[0].geometry.location);
//add markers here
var marker = new google.maps.Marker({
position: latLong,
map: map
});
});
}
}
getLatLongAndAddMarkers(address);
I am trying to load Map data using a CSV file using Google's Map API. I tried following this example: https://wrightshq.com/playground/placing-multiple-markers-on-a-google-map-using-api-3/
I was trying to load it which shows some information on clicking the markers.
My CSV data looks something like this
LGA_NAME Lat Long Information
DANDENONG -37.98862 145.21805 something crashed
DANDENONG -37.98862 145.21805 something crashed
DANDENONG -37.98862 145.21805 something crashed
DANDENONG -37.98862 145.21805 something crashed
DANDENONG -37.98862 145.21805 something crashed
https://jsfiddle.net/sourabhtewari/ye96s94c/2/
I cant seem to load any of the data. It shows up a blank. Not sure what could be the problem. If someone could correct it, I would be thankful.
function initialize() {
var map;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'roadmap'
};
// Display a map on the page
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
map.setTilt(45);
// Multiple Markers
var markers = [];
// Info Window Content
var infoWindowContent = [];
$.get('https://dl.dropboxusercontent.com/u/97162408/crashdata.csv', function(data) {
var data = csvToArray(data);
data.forEach(function(item) {
{
markers.push([item.LGA_NAME, parseFloat(item.Lat), parseFloat(item.Long)]);
infoWindowContent.push([item.Information]);
}
});
});
console.log(infoWindowContent);
function csvToArray(csvString) {
// The array we're going to build
var csvArray = [];
// Break it into rows to start
var csvRows = csvString.split(/\n/);
// Take off the first line to get the headers, then split that into an array
var csvHeaders = csvRows.shift().split(',');
// Loop through remaining rows
for (var rowIndex = 0; rowIndex < csvRows.length; ++rowIndex) {
var rowArray = csvRows[rowIndex].split(',');
// Create a new row object to store our data.
var rowObject = csvArray[rowIndex] = {};
// Then iterate through the remaining properties and use the headers as keys
for (var propIndex = 0; propIndex < rowArray.length; ++propIndex) {
// Grab the value from the row array we're looping through...
var propValue = rowArray[propIndex];
// ...also grab the relevant header (the RegExp in both of these removes quotes)
var propLabel = csvHeaders[propIndex];
rowObject[propLabel] = propValue;
}
}
return csvArray;
}
// 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]
});
// 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));
// Automatically center the map fitting all markers on the screen
map.fitBounds(bounds);
}
// Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
this.setZoom(14);
google.maps.event.removeListener(boundsListener);
});
}
$.get was out of scope for the needed objects. Silly mistake but a fix is easy.
fiddle: https://jsfiddle.net/sourabhtewari/aLk0c2fa/
$.get('https://dl.dropboxusercontent.com/u/97162408/crashdata.csv', function(data) {
function initialize() {
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// Display a map on the page
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
map.setTilt(45);
// Multiple Markers
var markers = [];
// Info Window Content
var infoWindowContent = [];
data = csvToArray(data);
data.forEach(function(item) {
markers.push([item.LGA_NAME, parseFloat(item.Lat), parseFloat(item.Long)]);
infoWindowContent.push([item.Information]);
});
// 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 - 1; i++) {
console.log(markers[i][1]);
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]
});
// 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));
// Automatically center the map fitting all markers on the screen
map.fitBounds(bounds);
}
// Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
this.setZoom(8);
google.maps.event.removeListener(boundsListener);
});
}
initialize();
});
function csvToArray(csvString) {
// The array we're going to build
var csvArray = [];
// Break it into rows to start
var csvRows = csvString.split(/\n/);
// Take off the first line to get the headers, then split that into an array
var csvHeaders = csvRows.shift().split(',');
// Loop through remaining rows
for (var rowIndex = 0; rowIndex < csvRows.length; ++rowIndex) {
var rowArray = csvRows[rowIndex].split(',');
// Create a new row object to store our data.
var rowObject = csvArray[rowIndex] = {};
// Then iterate through the remaining properties and use the headers as keys
for (var propIndex = 0; propIndex < rowArray.length; ++propIndex) {
// Grab the value from the row array we're looping through...
var propValue = rowArray[propIndex];
// ...also grab the relevant header (the RegExp in both of these removes quotes)
var propLabel = csvHeaders[propIndex];
rowObject[propLabel.trim()] = propValue;
}
}
return csvArray;
}
I'm having trouble getting my map to clear the clusters on a new search. Any ideas?
function clearLocations() {
//infoWindow.close();
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers.length = 0;
// clear #side_bar bottom text
document.getElementById("side_bar").innerHTML = "";
// clear .alertBox text
$('.alertBox').html('');
}
function searchLocationsNear(center) {
clearLocations();
var searchUrl = 'phpsqlsearch_genxml.php?lat=' + center.lat() + '&lng=' + center.lng();
downloadUrl(searchUrl, function (data) {
var xml = parseXml(data);
var markerNodes = xml.documentElement.getElementsByTagName("marker");
if (markerNodes.length > 0) {
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markerNodes.length; i++) {
var name = markerNodes[i].getAttribute("name");
var address = markerNodes[i].getAttribute("address");
var distance = parseFloat(markerNodes[i].getAttribute("distance"));
var category = markerNodes[i].getAttribute("category");
var latlng = new google.maps.LatLng(
parseFloat(markerNodes[i].getAttribute("lat")),
parseFloat(markerNodes[i].getAttribute("lng")));
// createOption(name, distance, i);
createMarker(latlng, name, address, category);
bounds.extend(latlng);
}
map.fitBounds(bounds);
var markerclusterer = new MarkerClusterer(map, markers);
// markerclusterer.setMap(null);
makeSidebar();
} else {
$('.alertBox').html('Sorry, there are no jobs that are close to your location.');
}
});
}
You should try this :
if (markers) {
for (i in markers) {
markers[i].setMap(null);
}
markers = [];
markerclusterer.clearMarkers()
}
According to the docs the clusterer can be clear with clearMarkers() method.
UPDATE
Call clear only when we have already create the MarkerClusterer.
if(markerclusterer)
{
clearLocations();
}
This question already has answers here:
Google Maps JS API v3 - Simple Multiple Marker Example
(15 answers)
Closed 9 years ago.
I was able to pull in my markers from an XML file and place them on a Google Map, but now I want each marker to link to its respective url once clicked. Can someone please let me know what I'm doing wrong? For some reason I'm only getting the last entry's url.
downLoad("phpsqlajax.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var city = markers[i].getAttribute("city");
var state = markers[i].getAttribute("state");
var country = markers[i].getAttribute("country");
var markerUrl = markers[i].getAttribute("url");
var point = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")));
var marker = new google.maps.Marker({
position: point,
map: googleMap,
icon: 'map-pin.png',
url: markerUrl
});
google.maps.event.addListener(marker, 'click', function() {
window.location.href = marker.url;
});
}
});
Make a create Marker function like this (not tested):
function createMarker(point, url) {
var marker = new google.maps.Marker({
position: point,
map: googleMap,
icon: 'map-pin.png',
url: markerUrl
});
google.maps.event.addListener(marker, 'click', function() {
window.location.href = marker.url;
});
}
Then call it like this:
downLoad("phpsqlajax.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var city = markers[i].getAttribute("city");
var state = markers[i].getAttribute("state");
var country = markers[i].getAttribute("country");
var markerUrl = markers[i].getAttribute("url");
var point = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")));
createMarker(point, markerUrl);
}
});