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);
};
Related
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);
}
I have a strange scenario with regards to a Polyline that is being drawn on the map. Before I post the code, I'll first demonstrate what happens when I make use of the normal direction services (Both calculates the resulting disctance the same = Total Distance: 62.734 km):
Now, when I draw the directions myself - this straight line appears out of nowhere:
Code snippet:
<script type="text/javascript">
var markers = [
{
"lat": '-26.2036247253418',
"lng": '28.0086193084717'
}
,
{
"lat": '-26.1259479522705',
"lng": '27.9742794036865'
}
,
{
"lat": '-25.8434619903564',
"lng": '28.2100086212158'
}
];
window.onload = function () {
var mapOptions = {
center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var labelIndex = 0;
var totalDistance = 0;
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
var infoWindow = new google.maps.InfoWindow();
var lat_lng = new Array();
var latlngbounds = new google.maps.LatLngBounds();
//var image = 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png';
for (i = 0; i < markers.length; i++) {
var data = markers[i]
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
lat_lng.push(myLatlng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: data.title,
label: labels[labelIndex++ % labels.length],
//icon: image
});
latlngbounds.extend(marker.position);
(function (marker, data) {
// google.maps.event.addListener(marker, "click", function (e) {
// infoWindow.setContent(data.description);
// infoWindow.open(map, marker);
// });
})(marker, data);
}
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds);
//***********ROUTING****************//
//Initialize the Path Array
var path = new google.maps.MVCArray();
//Initialize the Direction Service
var service = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer({
setMap: map
});
//Set the Path Stroke Color
var poly = new google.maps.Polyline({ map: map, strokeColor: '#4986E7' });
//Loop and Draw Path Route between the Points on MAP
for (var i = 0; i < lat_lng.length; i++) {
if ((i + 1) < lat_lng.length) {
var src = lat_lng[i];
var des = lat_lng[i + 1];
path.push(src);
//poly.strokeColor = '#'+Math.floor(Math.random()*16777215).toString(16);
poly.setPath(path);
service.route({
origin: src,
destination: des,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function (result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
var myroute = directionsDisplay.directions.routes[0];
var distance = 0;
for (i = 0; i < myroute.legs.length; i++) {
distance += myroute.legs[i].distance.value;
//for each 'leg'(route between two waypoints) we get the distance and add it to the total
}
for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
path.push(result.routes[0].overview_path[i]);
//console.log(result.routes[0].legs[0].distance);
}
totalDistance += distance;
document.getElementById('total').innerHTML = (totalDistance / 1000) + ' km';
}
});
}
}
}
</script>
<div id="dvMap"></div>
<div><p>Total Distance: <span id="total"></span></p></div>
Ok, so to solve the problem. Just remove the following line:
Reference: Google Documentation - Simple Polylines
And like that, the line is gone:
Aren't you also drawing a line between the first and last poly?
You should only draw lines between poly0 and poly1, poly1 and poly2 etc. but not poly100 and poly0 (if poly100 is the last one)
That would explain the straight line going from point B to A completing the shape. you don't want to complete the shape, so stop drawing. is there no function you can set to not complete the shape?
I only know of a very expensive work around and that is to trace back in reverse order from B to A along the same route. But that is probably not what you are looking for
I'm trying to place 3 markers on Google Map.
In JavaScript I wrote my loop as below
var places = ["Bondi Beach", "Coogee Beach", "Cronulla Beach"];
var lat = [-33.890542, -33.923036, -34.028249];
var lng = [151.274856, 151.259052, 151.157507];
var z=0;
for (tot=lat.length; z < tot; z++) {
var locations = [
[places[z], lat[z], lng[z]]
];
}
Then I initialized my map
var map;
var markers = [];
function init(){
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 10,
center: new google.maps.LatLng(-33.92, 151.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var num_markers = locations.length;
for (var i = 0; i < num_markers; i++) {
markers[i] = new google.maps.Marker({
position: {lat:locations[i][1], lng:locations[i][2]},
map: map,
html: locations[i][0],
id: i,
});
google.maps.event.addListener(markers[i], 'click', function(){
var infowindow = new google.maps.InfoWindow({
id: this.id,
content:this.html,
position:this.getPosition()
});
google.maps.event.addListenerOnce(infowindow, 'closeclick', function(){
markers[this.id].setVisible(true);
});
this.setVisible(false);
infowindow.open(map);
});
}
}
init();
However this output only one marker (the last one), I'm wondering what is wrong with my loop?
for (tot=lat.length; z < tot; z++) {
var locations = [
[places[z], lat[z], lng[z]]
];
}
Here you're overwriting the locations array with every iteration.
Push the new elements into the array instead.
var locations = []
for (tot=lat.length; z < tot; z++) {
locations.push([places[z], lat[z], lng[z]]);
}
this is displaying marker on a map on giving lat and lng as 24.8 and 67.2
var marker = new google.maps.Marker({
position: new google.maps.LatLng(24.8, 67.2),
map: map,
title: 'Hello Karachi!' });
}
here is the function which alerts the lat and lng getting from database
function CallL()
{
var len = document.getElementById('slcLon').length;
for(var i=0; i<len ; i++)
{
alert(document.getElementById('slcLon').options[i].text);
}
var len2 = document.getElementById('slcLat').length;
for(var j=0; j<len2 ; j++)
{
alert(document.getElementById('slcLat').options[j].text);
}
}
Now what i want to do is to give lat and lng from this loop to POSITION in marker but when i try to pass loop there it gives me syntax error.
any help will be grateful displaying multiple markers on the map
Your question is not at all clear but you may want something like this:
var markers = [],
latitudes = document.getElementById('slcLat'),
longitudes = document.getElementById('slcLon');
for (var i = 0; i < latitudes.length; i++) {
for (var j = 0; j < longitudes.length; j++) {
markers.push(new google.maps.Marker({
position: new google.maps.LatLng(latitudes.options[i].text, longitudes.options[j].text),
map: map,
title: 'Hello Karachi!'
}));
}
}
This would produce an array of markers for every combination of latitude and longitude that can be found in your select.
Edit: You indicate in the comments you don't want every combination, and that there are the same number of latitudes and longitudes which have to be paired together. So:
var markers = [],
latitudes = document.getElementById('slcLat'),
longitudes = document.getElementById('slcLon');
for (var i = 0; i < latitudes.length; i++) {
markers.push(new google.maps.Marker({
position: new google.maps.LatLng(latitudes.options[i].text, longitudes.options[i].text),
map: map,
title: 'Hello Karachi!'
}));
}
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