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;
}
Related
im trying to delete a Marker from a Map via ajax request.
ajax request looks like this.
$(document).on('click','.deletebtn',function(){
var theid =$(this).parent().attr("id");
var obj = {
id:theid
}
$.ajax({
url:"http://localhost:3000/singleMarker",
method:"post",
contentType:"application/json",
data:JSON.stringify(obj),
dataType:"JSON",
processData: true,
success:function(responseData){
clearMarker(responseData);
}
});
});
the response will reply with a single obj {id:id, {lat:xxx,lng:yyy}}
next i turn the lat lng data into a marker obj:
var clearMarker = function(responseData){
//clearAll Markers from Map
var markers =[];
var temp ={};
var marker;
for(var key in responseData){
//create markers with latlng objs
temp ={lat:responseData[key].pos.lat,lng:responseData[key].pos.lng};
marker = new google.maps.Marker({
position:temp,
map:meineMap
});
markers.push(marker);
}
setMapOnAll(null,markers);
}
then setMapOnAll with map null should delete all markers from the map but is not doing so. why?
function setMapOnAll(map,markers) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
//markers[i].setVisible(false);
}
}
If you only ever have one marker, there is no need to maintain an array of markers (or to call setMapOnAll), move the marker declaration out of the clearMarker function, if the marker exists, set its map property to null, otherwise, it is the first marker, just create it.
var marker;
var clearMarker = function(responseData){
//clearAll Markers from Map
var temp ={};
for(var key in responseData){
//create markers with latlng objs
temp ={lat:responseData[key].pos.lat,lng:responseData[key].pos.lng};
if (marker && marker.setMap) marker.setMap(null);
marker = new google.maps.Marker({
position:temp,
map:meineMap
});
}
}
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);
JS FIDDLE HERE:
http://jsfiddle.net/useyourillusiontoo/g77np63c/1/
I've created a google map that plants markers down and allows my to filter then with checkboxes without the page or map reloading. Yay!
Next I added marker cluster which worked too. However, when I now click on my markers the cluster doesn't update. That is.. the number inside the cluster doesnt change to reflect markers that are being hidden/displayed.
When I zoom in the markers are still being hidden/displayed but its just the cluster doesn't show this when zoomed out.
I've pasted my code below and would love any advice because i've been scratching my head.
var map;
var infowindow;
var image = [];
var gmarkers = [];
var clusterMarkers = [];
function mapInit(){
var centerCoord = new google.maps.LatLng(53.01265600000,-1.466105200000);
var mapOptions = {
zoom: 6,
center: centerCoord,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
addLocation();
var markerCluster = new MarkerClusterer(map, clusterMarkers);
function addLocation(place,category) {
for (var x in points){
var development = points[x];
var location = new google.maps.LatLng(development.lat, development.lng);
storeMarker(location, development);
}
}
function storeMarker(location, development){
var latLng = location;
var storedmarker = new google.maps.Marker({
position: latLng
});
storedmarker.mycategory = development.tid;
google.maps.event.addListener(storedmarker, 'click', function() {
if(typeof infowindow != 'undefined') infowindow.close();
infowindow = new google.maps.InfoWindow({
content: "<h3>"+ development.name +"</h3><a href='http://www.bbc.co.uk'>Show more!</a>"
});
infowindow.open(map, storedmarker);
});
clusterMarkers.push(storedmarker);
}
function show(category) {
for (var i=0; i<clusterMarkers.length; i++) {
if (clusterMarkers[i].mycategory == category) {
clusterMarkers[i].setVisible(true);
}
}
document.getElementById(category+"box").checked = true;
}
function hide(category) {
for (var i=0; i<clusterMarkers.length; i++) {
if (clusterMarkers[i].mycategory == category) {
clusterMarkers[i].setVisible(false);
}
}
document.getElementById(category+"box").checked = false;
infowindow.close();
}
function boxclick(box,category) {
if (box.checked) {
show(category);
} else {
hide(category);
}
}
jQuery(document).ready(function($) {
$('.b2bfilter').click(function () {
boxclick(this, this.value);
});
});
}
jQuery(document).ready(function(){
mapInit();
});
added markers as requested. They are a basic JSON object
var points = [
{"name":"House","lat":"53.341265600000","lng":"- 1.466105200000","tid":"1"},
{"name":"Old house","lat":"53.361066200000","lng":"-1.465752700000","tid":"2"}]
setting the visible-property will not have an effect when a marker is inside a cluster, you must also remove/add the marker from/to the markerclusterer.
Possible solution:
observe the visible_changed -event of the markers:
google.maps.event.addListener(storedmarker,'visible_changed',function(){
markerCluster[(this.getVisible())?'addMarker':'removeMarker'](this)
});
http://jsfiddle.net/doktormolle/g77np63c/4/
another(possibly better) approach(especially whene there are a lot of markers, because the solution above will force a redraw of the clusters for each affected marker):
First collect all affected markers and then use addMarkers/showMarkers to toggle them:
function toggle(category, show) {
var markers = [];
for (var i = 0; i < clusterMarkers.length; i++) {
if (clusterMarkers[i].mycategory == category) {
markers.push(clusterMarkers[i]);
clusterMarkers[i].setVisible(show);
}
}
if (markers.length) {
markerCluster[(show) ? 'addMarkers' : 'removeMarkers'](markers);
}
if (!show && infowindow) infowindow.close();
}
function boxclick(box, category) {
toggle(category, box.checked);
}
jQuery(document).ready(function ($) {
$('.b2bfilter').click(function () {
boxclick(this, this.value);
});
});
http://jsfiddle.net/doktormolle/g77np63c/5/
My Google Map is showing correctly, also centering the map is working like a charm. But when I want to add some marker (just the marker, don't want to reload the whole map) nothing happens (there are no visible markers on the map).
My script looks like this:
function g_maps(){
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(48.2136522, 16.386172),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
}
function g_maps_marker(coordinates){
var locations = [ coordinates ];
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
visible: true
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
The (important) part of my ajax request looks like that:
...
success:function(data){
$('#pagination_content table').empty();
data = $.parseJSON(data);
i = 1;
coordinates = "";
for(var i in data.results) {
$('#content_table').append("blablabla");
coordinates += "['" + data.results[i].title + "', " + data.results[i].lat + ", " + data.results[i].lat + ", " + i++ + "], ";
};
coordinates = coordinates.slice(0, -2)
g_maps_marker(coordinates);
},
...
The output of coordinates is this:
['abc', 48.1857442, 48.1857442, 0], ['xyz', 48.2136522, 48.2136522, 1]
The function g_maps is called at the document.ready() event.
I'm using the API v3.
You are slicing coordinates = coordinates.slice(0, -2); and then again making an array out of coordinates like this var locations = [ coordinates ];.
I' am confused a bit. slice already gives you an array so why making an array again? Are you sure that your loop gets executed?
Maybe you should remove var locations = [ coordinates ]; from g_maps_marker and then try again. I hope it will work.
** Edit **
After analyzing code a bit further I found that you are trying to use string which looks like an array and then trying to loop around it. This will not work.
For example
a = "[1, 2, 3]";
b = [a];
b[0][0]; // => will result in [ and not in your desired element
You should use following code in-order to make array objects for coordinates.
i = 1;
coordinates = [];
for(var i in data.results)
{
$('#content_table').append("blablabla");
var coordinate = [];
coordinate.push(data.results[i].title);
coordinate.push(data.results[i].lat);
coordinate.push(data.results[i].lon);
coordinates.push(coordinate);
};
Also it seems that you forgot to use longitude while creating coordinates array and used latitude two times. I have fixed this in my code.
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(','));