Tried to create moving marker. But the marker create new not moving the same. I want moving marker with remove previous marker
function makeMarker(map) {
var icons = 'images/tvsxl.png';
setInterval(function(){ var markers = [];
$.post( "ajaxload.php?shop_id=<?php echo $outlet_id?>", function(data) {
var obj = $.parseJSON(data);
var value = obj['data'];
//console.log(value.length);
for (i = 0; i < value.length; i++) {
var myLatLng = new google.maps.LatLng(value[i].latitude ,value[i].longitude);
var marker = new google.maps.Marker( {position: myLatLng, map: map,icon: icons,title:value[i].name} );
markers.push(marker);
markers[i].setMap( map );
}
});
}, 3000);
Try to clear old markers before placing a new ones
for(var i=0; i<markers.length; i++){
markers[i].setMap(null);
}
//clear old markers form array
markers = [];
try this
markers[marker-index-value].setMap( null);
Related
I am trying to delete markers from my own google maps, but my code didnt work and I don't know why. Would you like to help me? Thanks!
Data in function removeMarkers() - markers.length, is stil empty, if I try to debug by console.log(markers.length);
var map;
var markers = [];
var infowindow = new google.maps.InfoWindow();
function initialize() {
var mapOptions = {
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: new google.maps.LatLng(49.8037633, 15.4749126)
};
map = new google.maps.Map(document.getElementById('map'), mapOptions);
google.maps.event.addDomListener(document.getElementById('add-markers'), 'click', addMarkers);
google.maps.event.addDomListener(document.getElementById('remove-markers'), 'click', removeMarkers);
}
function addMarkers() {
var markerCluster;
$.ajax({
type: 'GET',
url: 'get-places.php',
dataType: 'json',
success: function(data) {
var markers = [];
$.each(data, function(index, element) {
var latLng = new google.maps.LatLng(element.lat, element.lng);
var marker = new google.maps.Marker({
position: latLng,
map: map,
// icon: icon,
title: element.title
});
markers.push(marker);
var details = element.name;
bindInfoWindow(marker, map, infowindow, details);
});
markerCluster = new MarkerClusterer(map, markers, {
imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
});
}
});
}
function removeMarkers() {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
}
function bindInfoWindow(marker, map, infowindow, strDescription) {
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(strDescription);
infowindow.open(map, marker);
});
}
initialize();
Function addMarkers() works well, but removeMarkers() not.
You have a global variable as var markers = []; but you do not populate this when you get AJAX response back. What you do in function addMarkers() is populate the variable markers inside this function which is local to this function.
You will need to remove var markers = []; from function addMarkers() and instead use the global variable to populate markers from your AJAX response. Then you will be able to remove markers in removeMarkers function.
var markers = []; // this is global scope
function addMarkers(){
var markers = []; // remove this declaration in this function as it creates local scope
}
function removeMarkers(){
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers = []; // do not forget to set this empty
}
You should remove the re-declaration of markers array. Your removeMarkers function does not know about the markers array you're populating inside your success callback.
var markers = [];
...
success: function(data) {
var markers = []; // <- remove that redeclaration
I have rendered a map with markers, which are saved as long lat values in a local xlsx file.
My aim is to automatically zoom to all markers, which are loaded via an input file button. For this I am using the fitbounds() method from googlemaps API.
Partial Example
function handleFile(e) {
//Get the files from Upload control
var files = e.target.files;
var i, f;
//Loop through files
for (i = 0, f = files[i]; i != files.length; ++i) {
var reader = new FileReader();
var name = f.name;
reader.onload = function (e) {
var data = e.target.result;
var result;
var workbook = XLSX.read(data, { type: 'binary' });
var sheet_name_list = workbook.SheetNames;
sheet_name_list.forEach(function (y) { /* iterate through sheets */
//Convert the cell value to Json
var roa = XLSX.utils.sheet_to_json(workbook.Sheets[y]);
if (roa.length > 0) {
result = roa;
}
});
//create global infoWindow object
var infoWindow = new google.maps.InfoWindow();
var i, newMarker;
var gmarkers = [];
//loop over json format
for (i = 0, length = result.length; i < length; i++) {
var data = result[i];
//extract Lat Long values from result
latLng = new google.maps.LatLng(data.Latitude, data.Longitude);
//creating a marker and putting it on the map
newMarker = new google.maps.Marker({
position: latLng,
map: map
});
gmarkers.push(newMarker);
}
for (var i=0; i < gmarkers.length; i++) {
bounds = new google.maps.LatLngBounds();
loc = new google.maps.LatLng(gmarkers[i].position.lat(), gmarkers[i].position.lng());
bounds.extend(loc);
}
map.fitBounds(bounds);
}
}
}
};
reader.readAsArrayBuffer(f);
}
But if I run my html file, it zooms just to one marker. I suppose that it is the first marker of the gmarkers array.
However I want to achieve following result, with the full extent of my uploaded marker:
In my main.html you can see my initMap() function and the function which is called if the document is ready. In the document ready function the handlefunction () is called.
var map;
//Change event to dropdownlist
$(document).ready(function(){
a = $('#input-id').fileinput({
'showUpload': false,
'showPreview': false,
'showCaption': false
});
a.change(handleFile);
});
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 48.7758459, lng: 9.1829321},
zoom: 3,
mapTypeControl: false
});
}
You have a typo in your code. Move the initialization of the bounds outside the loop.
for (var i=0; i < gmarkers.length; i++) {
bounds = new google.maps.LatLngBounds();
loc = new google.maps.LatLng(gmarkers[i].position.lat(), gmarkers[i].position.lng());
bounds.extend(loc);
}
map.fitBounds(bounds);
should be:
bounds = new google.maps.LatLngBounds();
for (var i=0; i < gmarkers.length; i++) {
loc = new google.maps.LatLng(gmarkers[i].position.lat(), gmarkers[i].position.lng());
bounds.extend(loc);
}
map.fitBounds(bounds);
proof of concept fiddle
code snippet:
var result = [{
Latitude: 37.4419,
Longitude: -122.1419
}, {
Latitude: 37.44,
Longitude: -122.14
}, {
Latitude: 40.44,
Longitude: -75.14
}]
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var gmarkers = [];
//loop over json format
for (i = 0, length = result.length; i < length; i++) {
var data = result[i];
//extract Lat Long values from result
latLng = new google.maps.LatLng(data.Latitude, data.Longitude);
//creating a marker and putting it on the map
newMarker = new google.maps.Marker({
position: latLng,
map: map
});
gmarkers.push(newMarker);
}
bounds = new google.maps.LatLngBounds();
for (var i = 0; i < gmarkers.length; i++) {
loc = new google.maps.LatLng(gmarkers[i].position.lat(), gmarkers[i].position.lng());
bounds.extend(loc);
}
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>
This is another approach for your problem within 35 lines of code.
Make sure you pass the JSON object the right way and that you declare your classes within the appropriate lexical scope.
Make sure the JSON Object returns something like this:
const coords = [
{lat: 42.4, lng: 1.55},
{lat: 43.42, lng: 2.48},
{lat: 45.43, lng: 4.9}
];
Note I have changed result to a more meaningful coords array of objects.
// Create your markers without worrying about scope and without extensive For Loops
const markers = coords.map((coord) => {
return new google.maps.Marker({
position: new google.maps.LatLng(coord.lat, coord.lng),
map: map,
animation: google.maps.Animation.DROP
});
})
// Declare your bounds outside the map method (previous for loop)
const bounds = new google.maps.LatLngBounds();
// Iterate through markers and return coords for expanded viewport
markers.forEach((loc) =>{
loc = new google.maps.LatLng(loc.position.lat(), loc.position.lng());
return bounds.extend(loc);
});
map.fitBounds(bounds);
}
The function below does not remove the markers when called. Why?
// Remove existing markers from the Map
function removeMarkers(markersArray) {
var j,position;
for (j = 0; j < markersArray.length; j += 1){
position = new google.maps.Marker({
position: {lat: markersArray[j][1], lng: markersArray[j][2]}
});
position.setMap(null);
};
};
Here is the array that is being fed into the function:
var educationMarkers = [
['Grafton Campus, Auckland University', -36.861717, 174.769424],
["Auckland Boys' Grammar", -36.872432, 174.768126],
["Epsom Girls' Grammar", -36.876177, 174.773639],
["St. Peter's College", -36.868412, 174.768575],
["ACG Parnell College", -36.863163, 174.778555],
["Newmarket Campus, Auckland University", -36.865905, 174.7733]
];
You need to keep reference of the markers you placed.
var placedMarkers = [];
function placeMarkers(markersArray) {
var marker, i, postiion, bounds = new google.maps.LatLngBounds();
for (i = 0; i < markersArray.length; i += 1) {
marker = new google.maps.Marker({
map: map,
position: {
lat: markersArray[i][1],
lng: markersArray[i][2]
}
});
// keep reference of the markers you placed
placedMarkers.push(marker);
position = new google.maps.LatLng(markersArray[i][1], markersArray[i][2]);
bounds.extend(position);
}
map.fitBounds(bounds);
};
and when removing the markers, use the reference array you kept.
// Remove existing markers from the Map
function removeMarkers() {
var j,position;
// loop through reference array you kept.
for (j = 0; j < placedMarkers.length; j += 1){
placedMarkers[j].setMap(null);
};
};
If the markers in the loop are correct,Just change your for loop with this,Make a fiddler if possible
for (j = 0; j < markersArray.length; j += 1){
position[j] = new google.maps.Marker({
position: {lat: markersArray[j][1], lng: markersArray[j][2]}
});
position[j].setMap(null);
};
I need to assign 50 map markers for a google map. I don't want to have the (almost) same line of code 50 times. What is the best way to loop through this easily and optimize code?
var marker1 = new google.maps.Marker({position: new google.maps.LatLng(location1_latitude,location1_longitude),map: map1,title:location1});
var marker2 = new google.maps.Marker({position: new google.maps.LatLng(location2_latitude,location2_longitude),map: map1,title:location2});
var marker3 = ...
repeating to
var marker50 = new google.maps.Marker({position: new google.maps.LatLng(location50_latitude,location50_longitude),map: map1,title:location50});
you can use two arrays and iterate over them:
var location_latitude = [0,1,2,3,4,5] // all your latitudes
var location_longitude = [0,1,2,3,4,5] // all your longitudes
var location_titles = ['loc0','loc1','loc2','loc3','loc4','loc5']
var markers = []
for (var i = 0; i < location_latitude.length && i < location_longitude.length && i < location_titles.length; i++) {
markers[i] = new google.maps.Marker({position: new google.maps.LatLng(location_latitude[i],location_longitude[0]),map: map1,title:location_titles[i]});
}
you can also abstract lat, lng and title into an object:
var locations = [{lat: 0, lng: 0, title: 'latlng0'},{lat: 0, lng: 0, title: 'latlng0'}] // depending on how you get you're data, you'll want to adjust your loop's format so you don't have to manually convert it
var markers = []
for (var i = 0; i < locations.length; i++) {
var current = locations[i]
markers[i] = new google.maps.Marker({position: new google.maps.LatLng(current.lat,current.lng),map: map1,title:current.title});
}
so i works in a geolocation project(asp.net MVC4), i have many positions in my database and i want to show it in my map, my problem that the script just show the first position, this is my script:
var checkpoints = [];
function setMarkers(map, locations) {
for (var i = 0; i < locations.length; i++)
{
var place = locations;
for (var i = 0; i < place.length; i++)
{
var points = new google.maps.LatLng(place[i][1], place[i][2]);
checkpoints.push(points);
}
var check = checkpoints[0];
var index = 0;
for (var j = 0; j < checkpoints.length; j++)
{
check = checkpoints[j];
index = j;
var myLatLng = new google.maps.LatLng(place[index][1], place[index][2]);
var marker = new google.maps.Marker
(
{
position: myLatLng,
map: map,
title: place[index][0],
zIndex: place[index][3]
}
);
}
}
return marker;
}
so please if someone have any solution or idea i will be very appreciate.
Thanks everyone #david #Beetroot-Beetroot #razzak my script works fine now, this is my new script :
var checkpoints = [];
function setMarkers(map, locations) {
for (var i in locations) {
var points = new google.maps.LatLng(locations[i][1], locations[i][2]);
checkpoints.push(points);
var marker = new google.maps.Marker({
map: map,
position: points,
title: locations[i][0],
zindex: locations[i][4]
});
}
}
Update :
my script works fine but i have a small problem in my event, when i dblclick on a marker it should show his title but it just show me the title of the last marker :
var checkpoints = [];
function setMarkers(map, locations) {
for (var i in locations) {
var points = new google.maps.LatLng(locations[i][1], locations[i][2]);
checkpoints.push(points);
var marker = new google.maps.Marker({
map: map,
position: points,
title: locations[i][0],
zindex: locations[i][4],
});
//this is my event
google.maps.event.addListener(marker, 'dblclick', function () {
alert("I am marker " + marker.title);
});
}
}
I have simplified your code
function setMarkers(locations) {
for(var i in locations) {
var points = new google.maps.LatLng(locations[i][1].lat,locations[i][2].lng);
checkpoints.push(points);
var marker = new google.maps.Marker({
map:map,
position: points,
icon: 'myicon.png',//
title: locations[i][0],
zindex: locations[i][4]
});
}
}
Mohammadov, you are making it more complicated than it needs to be.
Try this :
function setMarkers(map, locations) {
for(var i=0; i<locations.length; i++) {
var loc = locations[i];
loc[4] = new google.maps.Marker({
position: new google.maps.LatLng(loc[1], loc[2]),
map: map,
title: loc[0],
zIndex: loc[3]
});
}
}
The map should then show the markers, and each member of the locations array should be augmented with a reference to its marker, as element [4].
the two loops inside the main loop are causing problems, they are unnecessary and can be avoided. also return marker at the end of the loop will return only the last one, you can remove it as well:
var checkpoints = [];
function setMarkers(map, locations) {
for (var i=0; i<locations.length; i++)
{
var place = locations[i],
myLatLng = new google.maps.LatLng(place[1], place[2]),
marker = new google.maps.Marker
(
{
position: myLatLng,
map: map,
title: place[0],
zIndex: place[3]
}
);
checkpoints.push({"point": myLatLng, "marker": marker});
}
}
The checkpoints now should have an array of LatLng and marker of each place.
jsfiddle