setMap(null) not working - javascript

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
});
}
}

Related

Google maps api and geocoding api - issues adding markers

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);

Loading Latitude longitude data using Google maps API using CSV data

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;
}

How can I filter google map marker using jQuery and json?

I want to put markers which satisfy conditions I set before.
So I did
$.get("/map/getspot", function(data, status){
for (var i = 0; i < data.length; i++){
if (data[i].name == "hello") {
var latlng = new google.maps.LatLng(data[i].lat, data[i].lng);
var marker = new google.maps.Marker({
position: latlng,
title:data[i].name,
map: map
});
marker.setMap(map);
}
}
});
In map/getspot, I have
[{"id":1,"name":"hello","lat":37.552021,"lng":126.935887,"spot_description":"haho","address":"help","created_at":"2015-08-01T07:23:28.645Z","updated_at":"2015-08-01T07:23:28.645Z"}]
I rendered it.
But the problem is, it doesn't work.
It works well(puts all markers on my map) when I erase
if(data[i].name == "hello")
what am I missing?

Get total marker count from Google API placesSearch

In the example fiddle, how can I get the total number of markers displayed on the map? I'm pushing each of the markers into an array like this:
markers.push(marker)
And attempting to get the total number of markers like this:
$('.marker-count span').html(markers.length);
Unfortunately, "markers.length" is returning 0 when it should be returning at least 3.
I have example code here: http://jsfiddle.net/287C7/
How can I display the total number of markers? Is it not possible to add each marker to my array?
I need to know the amount of markers shown so that I can alert the user if there are none.
Thanks,
In case you don't want to view the code on jsfiddle.net, here it is:
var map, places, tmpLatLng, markers = [];
var pos = new google.maps.LatLng(51.5033630,-0.1276250);
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(51.5033630,-0.1276250)
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// create the map and reference the div#map-canvas container
var markerBounds = new google.maps.LatLngBounds();
var service = new google.maps.places.PlacesService(map);
// fetch the existing places (ajax)
// and put them on the map
var request = {
location: pos,
radius: 48000, // Max radius
name: "mc donalds"
};
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
$('#map-canvas').attr("data-markers",results.length);
$('.marker-count span').html(markers.length);
} else {
console.log("Places request failed: "+status);
}
} // end callback
function createMarker(place) {
var prequest = {
reference: place.reference
};
var tmpLatLng = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
markers.push(marker);
markerBounds.extend( tmpLatLng );
} // end createMarker
service.nearbySearch(request, callback);
the placesSearch call is asynchronous, when you run your code:
$('.marker-count span').html(markers.length);
the result hasn't come back from the server yet. You need to do that in the call back after you update the markers array.
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
$('#map-canvas').attr("data-markers",results.length);
$('.marker-count span').html(markers.length);
} else {
console.log("Places request failed: "+status);
}
} // end callback
working fiddle

Google Maps - Creating multiple markers

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(','));

Categories