I am working with Google maps API(latest). So far, i can able to create and removing(on add operation) route with the help of polylines and markers.
Problem is when i try to modify(on update mode) the maps populates(dynamically) the route which i saved but if try to remove/modify existing route the marker removes but polyline dont.
tried poly.setMap(null);. but doesn't work.
on page load :
after removing any marker : (the last one got removed)
And you can see marker has been removed but polyline is still there
CODE(not working on fiddle):
var poly;
var map;
var markers = new Array();
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: {
lat: 24.926294,
lng: 67.022095
} // Center the map on Pakistan.
});
poly = new google.maps.Polyline({
strokeColor: '#000000',
strokeOpacity: 1.0,
strokeWeight: 3
});
poly.setMap(map);
// if update/edit model populate map dynamically
populateLatLng();
// Add a listener for the click event
map.addListener('click', addLatLng);
map.addListener('click', function() {
getPathVariableCode(poly);
});
}
function populateLatLng() {
var path = '[{"lat":24.96078338154793,"lng":67.10892827306634},{"lat":24.934323836524374,"lng":67.07047612462884},{"lat":24.926851877301345,"lng":67.08111912999993},{"lat":24.90816999805268,"lng":67.06669957433587},{"lat":24.917822655664953,"lng":67.0519366959179},{"lat":24.911102310371437,"lng":67.03740863310293}]' //dynamic array
path = JSON.parse(path);
for (k = 0; k < path.length; k++) {
var marker = new google.maps.Marker({
position: path[k],
title: '#' + k,
map: map
});
markers.push(marker);
poly = new google.maps.Polyline({
path: path,
strokeColor: '#000000',
strokeOpacity: 1.0,
strokeWeight: 3
});
poly.setMap(map);
google.maps.event.addListener(marker, 'click', function(event) {
removePoint(marker);
});
}
}
// Handles click events on a map, and adds a new point to the Polyline.
function addLatLng(event) {
console.log("event", event);
var path = poly.getPath();
// Because path is an MVCArray, we can simply append a new coordinate
// and it will automatically appear.
path.push(event.latLng);
// Add a new marker at the new plotted point on the polyline.
var marker = new google.maps.Marker({
position: event.latLng,
title: '#' + path.getLength(),
map: map
});
markers.push(marker);
console.log(markers.length - 1, event.latLng);
poly.getPath().setAt(markers.length - 1, event.latLng);
google.maps.event.addListener(marker, 'click', function(event) {
removePoint(marker);
});
}
function getPathVariableCode(line) {
var getLocation = '';
var locationArr = [];
var pathArr = line.getPath();
for (var i = 0; i < pathArr.length; i++) {
var codeStr = [];
codeStr = {
'lat': pathArr.getAt(i).lat(),
'lng': pathArr.getAt(i).lng()
};
locationArr.push(codeStr);
document.getElementById('locationCordinates').value = JSON.stringify(locationArr);
}
};
function removePoint(marker) {
for (var i = 0; i < markers.length; i++) {
if (markers[i] === marker) {
markers[i].setMap(null);
markers.splice(i, 1);
poly.getPath().removeAt(i);
getPathVariableCode(poly);
}
}
}
#map {
height: 200px;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="//maps.googleapis.com/maps/api/js?key=API_KEY&callback=initMap">
</script>
Your code is quite problematic but I was able to successfully get a simplified working version of what you're trying to achieve here (if I understood correctly).
Try the code below. Just click on the map to add markers and then click on those markers to remove both the markers and their corresponding lines.
var poly;
var map;
var markers = new Array();
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: {
lat: 24.926294,
lng: 67.022095
} // Center the map on Pakistan.
});
poly = new google.maps.Polyline({
strokeColor: '#000000',
strokeOpacity: 1.0,
strokeWeight: 3
});
poly.setMap(map);
// Add a listener for the click event
map.addListener('click', addLatLng);
}
// Handles click events on a map, and adds a new point to the Polyline.
function addLatLng(event, path = false) {
console.log("event", event);
var path = poly.getPath();
// Because path is an MVCArray, we can simply append a new coordinate
// and it will automatically appear.
path.push(event.latLng);
// Add a new marker at the new plotted point on the polyline.
var marker = new google.maps.Marker({
position: event.latLng,
title: '#' + path.getLength(),
map: map,
id: new Date()
});
markers.push(marker);
console.log(markers.length - 1, event.latLng);
poly.getPath().setAt(markers.length - 1, event.latLng);
google.maps.event.addListener(marker, 'click', function(event) {
removePoint(marker);
});
}
function removePoint(marker) {
for (var i = 0; i < markers.length; i++) {
if (markers[i].id === marker.id) {
markers[i].setMap(null);
markers.splice(i, 1);
poly.getPath().removeAt(i);
}
}
}
I hope this helps point you in the right direction.
Related
I'm doing an application with google maps API that have a JSON with the marker's coordinates. Then I draw polylines between the markers. I also implemented a function with a onclick event that creates a new marker inside the polyline. This marker has to show information of the previous marker in the polyline (the one taked of the JSON, not a clicked one). But I don't know how to take the previous vertex(marker) of a selected polyline.
Code:
(function() {
window.onload = function() {
var options = {
zoom: 3,
center: new google.maps.LatLng(37.09, -95.71),
mapTypeId: google.maps.MapTypeId.HYBRID,
noClear: true,
panControl: true,
scaleControl: false,
streetViewControl:false,
overviewMapControl:false,
rotateControl:false,
mapTypeControl: true,
zoomControl: false,
};
var map = new google.maps.Map(document.getElementById('map'), options);
// JSON
$.getJSON("loc.js", function(json) {
console.log(json);
});
//Marker type
var markers = [];
var arr = [];
var pinColor = "FE7569";
var pinImage = new google.maps.MarkerImage("http://labs.google.com/ridefinder/images/mm_20_red.png" + pinColor,
new google.maps.Size(21, 34),
new google.maps.Point(0,0),
new google.maps.Point(10, 34));
// JSON loop
for (var i = 0, length = json.length; i < length; i++) {
var data = json[i],
latLng = new google.maps.LatLng(data.lat, data.lng);
arr.push(latLng);
// Create markers
var marker = new google.maps.Marker({
position: latLng,
map: map,
icon: pinImage,
});
infoBox(map, marker, data);
//Polylines
var flightPath = new google.maps.Polyline({
path: json,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2,
map:map
});
infoPoly(map, flightPath, data);
//Calculate polylines distance
google.maps.LatLng.prototype.kmTo = function(a){
var e = Math, ra = e.PI/180;
var b = this.lat() * ra, c = a.lat() * ra, d = b - c;
var g = this.lng() * ra - a.lng() * ra;
var f = 2 * e.asin(e.sqrt(e.pow(e.sin(d/2), 2) + e.cos(b) * e.cos
(c) * e.pow(e.sin(g/2), 2)));
return f * 6378.137;
}
google.maps.Polyline.prototype.inKm = function(n){
var a = this.getPath(n), len = a.getLength(), dist = 0;
for (var i=0; i < len-1; i++) {
dist += a.getAt(i).kmTo(a.getAt(i+1));
}
return dist;
}
}
function infoBox(map, marker, data) {
var infoWindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, "click", function(e) {
salta(data.tm);
});
(function(marker, data) {
google.maps.event.addListener(marker, "click", function(e) {
salta(data.tm);
});
})(marker, data);
}
//Create onclick marker on the polyline
function infoPoly(map, flightPath, data){
google.maps.event.addListener(flightPath, 'click', function(event) {
mk = new google.maps.Marker({
map: map,
position: event.latLng,
});
markers.push(mk);
map.setZoom(17);
map.setCenter(mk.getPosition());
});
}
function drawPath() {
var coords = [];
for (var i = 0; i < markers.length; i++) {
coords.push(markers[i].getPosition());
}
flightPath.setPath(coords);
}
// Fit these bounds to the map
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < arr.length; i++) {
bounds.extend(arr[i]);
}
map.fitBounds(bounds);
//dist polylines
distpoly = flightPath.inKm();
distpolyround = Math.round(distpoly);
};
})();
If I click in the blue arrow, I create a marker on that point of the polyline. I that marker it takes the values of the previous one.
You can use the geometry library .poly namespace isLocationOnEdge method to determine which segment of the polyline the clicked point (new marker) is on.
//Create onclick marker on the polyline
function infoPoly(map, flightPath, data) {
google.maps.event.addListener(flightPath, 'click', function(event) {
mk = new google.maps.Marker({
map: map,
position: event.latLng,
});
markers.push(mk);
map.setZoom(17);
map.setCenter(mk.getPosition());
// find line segment. Iterate through the polyline checking each line segment.
// isLocationOnEdge takes a google.maps.Polyline as the second argument, so make one,
// then use it for the test. The default value of 10e-9 for the tolerance didn't work,
// a tolerance of 10e-6 seems to work.
var betweenStr = "result no found";
var betweenStr = "result no found";
for (var i=0; i<flightPath.getPath().getLength()-1; i++) {
var tempPoly = new google.maps.Polyline({
path: [flightPath.getPath().getAt(i), flightPath.getPath().getAt(i+1)]
})
if (google.maps.geometry.poly.isLocationOnEdge(mk.getPosition(), tempPoly, 10e-6)) {
betweenStr = "between "+i+ " and "+(i+1);
}
}
(function(mk, betweenStr) {
google.maps.event.addListener(mk, "click", function(e) {
infowindow.setContent(betweenStr+"<br>loc:" + this.getPosition().toUrlValue(6));
infowindow.open(map, mk);
// salta(data.tm);
});
})(mk, betweenStr);
google.maps.event.trigger(mk,'click');
});
proof of concept fiddle
code snippet:
var infowindow = new google.maps.InfoWindow();
(function() {
window.onload = function() {
var options = {
zoom: 3,
center: new google.maps.LatLng(37.09, -95.71),
mapTypeId: google.maps.MapTypeId.HYBRID,
};
var map = new google.maps.Map(document.getElementById('map'), options);
//Marker type
var markers = [];
var arr = [];
var pinColor = "FE7569";
var pinImage = "http://labs.google.com/ridefinder/images/mm_20_red.png";
// JSON loop
for (var i = 0, length = json.length; i < length; i++) {
var data = json[i],
latLng = new google.maps.LatLng(data.lat, data.lng);
arr.push(latLng);
// Create markers
var marker = new google.maps.Marker({
position: latLng,
map: map,
icon: pinImage,
});
infoBox(map, marker, data);
//Polylines
var flightPath = new google.maps.Polyline({
path: json,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2,
map: map
});
infoPoly(map, flightPath, data);
}
function infoBox(map, marker, data) {
var infoWindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, "click", function(e) {
infowindow.setContent("tm:" + data.tm + "<br>loc:" + this.getPosition().toUrlValue(6));
infowindow.open(map, marker);
// salta(data.tm);
});
(function(marker, data) {
google.maps.event.addListener(marker, "click", function(e) {
infowindow.setContent("tm:" + data.tm + "<br>loc:" + this.getPosition().toUrlValue(6));
infowindow.open(map, marker);
// salta(data.tm);
});
})(marker, data);
}
//Create onclick marker on the polyline
function infoPoly(map, flightPath, data) {
google.maps.event.addListener(flightPath, 'click', function(event) {
mk = new google.maps.Marker({
map: map,
position: event.latLng,
});
markers.push(mk);
map.setZoom(17);
map.setCenter(mk.getPosition());
// find line segment. Iterate through the polyline checking each line segment.
// isLocationOnEdge takes a google.maps.Polyline as the second argument, so make one,
// then use it for the test. The default value of 10e-9 for the tolerance didn't work,
// a tolerance of 10e-6 seems to work.
var betweenStr = "result no found";
for (var i = 0; i < flightPath.getPath().getLength() - 1; i++) {
var tempPoly = new google.maps.Polyline({
path: [flightPath.getPath().getAt(i), flightPath.getPath().getAt(i + 1)]
})
if (google.maps.geometry.poly.isLocationOnEdge(mk.getPosition(), tempPoly, 10e-6)) {
betweenStr = "between " + i + " and " + (i + 1);
}
}
(function(mk, betweenStr) {
google.maps.event.addListener(mk, "click", function(e) {
infowindow.setContent(betweenStr + "<br>loc:" + this.getPosition().toUrlValue(6));
infowindow.open(map, mk);
// salta(data.tm);
});
})(mk, betweenStr);
google.maps.event.trigger(mk, 'click');
});
}
function drawPath() {
var coords = [];
for (var i = 0; i < markers.length; i++) {
coords.push(markers[i].getPosition());
}
flightPath.setPath(coords);
}
// Fit these bounds to the map
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < arr.length; i++) {
bounds.extend(arr[i]);
}
map.fitBounds(bounds);
//dist polylines
distpoly = flightPath.inKm();
distpolyround = Math.round(distpoly);
};
})();
var json = [{
lat: 38.931808,
lng: -74.906606,
tm: 0
}, {
lat: 38.932442,
lng: -74.905147,
tm: 1
}, {
lat: 38.93311,
lng: -74.903473,
tm: 2
}, {
lat: 38.933777,
lng: -74.901671,
tm: 3
}, {
lat: 38.930739,
lng: -74.912528,
tm: 1000
}];
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
<div id="map"></div>
INITIALIZING
When you are creating those markers in the for loop, add them to a map [Data structure] that you define (empty) before the loop. In the map markers will be stored. Their keys - concatenated lat/lng.
var initial_markers = {}; //before for loop
initial_markers[data.lat+"-"+data.lng] = marker; //after each marker initialization
Count them, so you know how many there are initial_marker_count, because you cannot get length of size of a map[data structure]
DETECTION
When you have clicked on a polyline, I don't think you can get exactly the part of polyline that is clicked, so you need to get it yourself. The steps are:
Get the coordinate of click event
Loop through the markers
Take their coordinates
Check if the clicked point on the map is on the line between those two points
If is, take the first of those two points
DETECTION PSEUDOCODE
var prev_marker;
for (var i=initial_markers; i<initial_marker_count-2; i++) {
if( isPointOnLine(initial_markers[i], initial_markers[i+1], clicked_point) {
prev_marker = initial_markers[i];
break;
}
}
The only reason I am saying that this is pseudocode, is because I don't know hor to find if point is on the line between two points in Google maps. And you should write that isPointOnLine() functions. Apart from that - the idea is given. Hope You appreciate it.
Hi i'm trying to get markers latlon from ajax, i m getting ajax data every second and also able to create marker within radius , now i'm facing problem with updating marker positions as in current new marker created and old one also showing. Pls help to update markers which i am getting from ajax and remove extra.
var map = null;
var geocoder = null;
var markers = {};
var infoWindow = null;
var minZoomLevel = 16;
jQuery('#search').click(function() {
var address = jQuery('#address').val() || 'India';
if (map === null)
initializeMap();
searchAddress(address);
});
function initializeMap() {
var mapOptions = {
zoom: minZoomLevel,
draggable: true,
disableDefaultUI: true,
scrollwheel: true,
disableDoubleClickZoom: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(initialLocation);
// Limit the zoom level
google.maps.event.addListener(map, 'zoom_changed', function () {
if (map.getZoom() < minZoomLevel) map.setZoom(minZoomLevel);
});
});
}
google.maps.event.addListener(map, "idle", function(event) {
searchStoresBounds();
});
geocoder = new google.maps.Geocoder();
infoWindow = new google.maps.InfoWindow();
}
function searchAddress(address) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
var latlng = results[0].geometry.location;
map.setCenter(latlng);
// Limit the zoom level
google.maps.event.addListener(map, 'zoom_changed', function () {
if (map.getZoom() < minZoomLevel) map.setZoom(minZoomLevel);
});
searchStoresBounds();
} else {
alert('Geocode was failed: ' + status);
}
});
}
setInterval(function searchStoresBounds() {
var bounds = map.getCenter().toUrlValue();
var url = './store.php';
var parameter = { bounds: bounds };
jQuery.ajax({
url: url,
data: parameter,
dataType: 'json',
success: showStores
});
}, 1000);
function showStores(data, status, xhr) {
if (data['status'] != 'OK')
return;
var id;
// add markers for new stores
for (id in data['data']) {
if (markers[id] === undefined)
createMarker(id, data['data'][id]);
}
var b = map.getBounds();
// remove markers out of the bounds
for (id in markers) {
if (! b.contains(markers[id].getPosition())) {
markers[id].setMap(null);
delete markers[id];
}else{createMarker(id, data['data'][id]);}
}
}
function createMarker(id, store) {
var latlng = new google.maps.LatLng(
parseFloat(store['lat']),
parseFloat(store['lng'])
);
var html = "<b>" + store['address'] + "</b>";
var x = store['distance'];
var y = 1000;
var z = x * y;
var m = 85;
var t = z / m;
document.getElementById("demo").innerHTML = Math.ceil(t);
var headm = store['bearing'];
var car = "M17.402,0H5.643C2.526,0,0,3.467,0,6.584v34.804c0,3.116,2.526,5.644,5.643,5.644h11.759c3.116,0,5.644-
2.527,5.644-5.644 V6.584C23.044,3.467,20.518,0,17.402,0z M22.057,14.188v11.665l-2.729,0.351v-4.806L22.057,14.188z
M20.625,10.773 c-1.016,3.9-2.219,8.51-2.219,8.51H4.638l-2.222-8.51C2.417,10.773,11.3,7.755,20.625,10.773z
M3.748,21.713v4.492l-2.73-0.349 V14.502L3.748,21.713z M1.018,37.938V27.579l2.73,0.343v8.196L1.018,37.938z
M2.575,40.882l2.218-3.336h13.771l2.219,3.336H2.575z M19.328,35.805v-7.872l2.729-0.355v10.048L19.328,35.805z";
var icon = {
path: car,
scale: .7,
strokeColor: 'White',
strokeWeight: .4,
fillOpacity: 1,
fillColor: '#333333',
offset: '5%',
rotation: parseInt(headm),
// rotation: parseInt(heading[i]),
anchor: new google.maps.Point(10, 25) // orig 10,50 back of car, 10,0 front of car, 10,25 center of car
};
var marker = new google.maps.Marker({
map: map,
position: latlng,
icon: icon,
});
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
markers[id] = marker;
}
You are facing the issue due to this part
var marker = new google.maps.Marker({
map: map,
position: latlng,
icon: icon,
});
Everytime you get data from ajax it creates a new marker.
Add the following declaration at the top of your js page
var marker;
and change the marker creation to the following
if(marker)
{
marker.setMap(null);
}
marker = new google.maps.Marker({
map: map,
position: latlng,
icon: icon,
});
Before you create a new marker the previous one is removed from the map. The if(marker) part is needed to check if a marker instance has been created because the first time that you run there will be no marker and you will get an error while trying to remove the marker.
Edit 1 :
As you have multiple markers you will need to store an array of markers and remove them before adding new markers on map
At the top of the page you will need to declare
var markerArray = new Array();
Just before you add the markers you will need to clear the previous markers
for(var i = 0; i<markerArray.length; i++)
{
markerArray[i].setMap(null);
}
markerArray = new Array()
After that will be your current code
var marker = new google.maps.Marker({
map: map,
position: latlng,
icon: icon,
});
markerArray.push(marker);
You will need to add the marker to the markerArray so that it can be cleared the next time your code executes.
When Google Map load, it cost several seconds to load all submaps, each time i want to change a marker i need to load all map again and again, it is possible to load map once and update markers dynamic?
function initialize(markers) {
console.log(markers);
var mapOptions = {
zoom: 7,
center: new google.maps.LatLng(40.4378271,-3.6795367)
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var j=0;
for (var i=0;i<((markers.length)-3);i=i+3){
var marker = new google.maps.Marker({
position: new google.maps.LatLng(markers[i],markers[i+1]),
map: map,
icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld='+j+'|FE6256|000000',
title: markers[i+2]
});
j++;
}
}
google.maps.event.addDomListener(window, 'load', initialize(markers()));
You must store the Map-instance somewhere where it's accessible inside initialize, then you'll be able to re-use the Map on further calls and must only remove previous markers and draw the new markers.
Sample(stores the Map as property of the map-div):
function initialize(markers) {
var node = document.getElementById('map-canvas'),
j = 0,
marker;
//create a single Map-instance and store it as property of the map-container
if (!node.map) {
//create a MVCObject, used for binding of the markers map-property
node.mvc = new google.maps.MVCObject();
//the map
node.map = new google.maps.Map(node, {
zoom: 2,
center: new google.maps.LatLng(40.4378271, -3.6795367)
});
}
//this will remove previous markers
node.mvc.set('map', null);
node.mvc.set('map', node.map);
for (var i = 0; i < ((markers.length) - 3); i = i + 3) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(markers[i], markers[i + 1]),
map: node.map,
icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=' +
j + '|FE6256|000000',
title: markers[i + 2]
});
//bind the markers map-property
marker.bindTo('map', node.mvc, 'map', true);
google.maps.event.addListener(marker, 'map_changed', function () {
//remove the binding when map has been set to null
if (!this.getMap()) {
this.unbind('map');
}
});
j++;
}
}
Demo: http://jsfiddle.net/doktormolle/ns7j3sx0/
function disp_initialize()
{
var bike=<?php echo $_GET['bike_id']; ?>;
$.ajax({
"dataType": "json",
"type": "POST",
"url": "home.php?bike_id="+bike,
success: function(data) {
if(data.sMsg==0)
{
$("#map-canvas").hide();
}
else if(data.sBlankMsg==0){
$("#map-canvas").hide();
}
else
{
initialize(data);
}
}
});
}
function initialize(flightPlanCoordinates_arr)
{
var flightPlanCoordinates_arr = flightPlanCoordinates_arr.mapData;
var flightPlanCoordinates_arr_p = new Array();
var j = 0;var k = 0;
var store = new Array();
for(var i in flightPlanCoordinates_arr)
{
if(j==0)
{
flightPlanCoordinates_arr_p[j] = flightPlanCoordinates_arr[i];
j++;
}
else if(flightPlanCoordinates_arr_p[j-1]['state']==1 && flightPlanCoordinates_arr[i]['state']==0)
{
flightPlanCoordinates_arr_p[j] = flightPlanCoordinates_arr[i];
j++;
}
else if(flightPlanCoordinates_arr_p[j-1]['state']==0 && flightPlanCoordinates_arr[i]['state']==1)
{
store[k]=j;
flightPlanCoordinates_arr_p[j] = flightPlanCoordinates_arr[i];
j++;k++;
}
}
//console.log(store);
var flightPlanCoordinates = new Array();
for(var i in flightPlanCoordinates_arr_p)
{
flightPlanCoordinates[i] = new google.maps.LatLng(flightPlanCoordinates_arr_p[i]["latitude"],flightPlanCoordinates_arr_p[i]["longitude"]);
}
if(flightPlanCoordinates_arr != '')
{
var mapOptions = {
zoom: 10,
center: new google.maps.LatLng(flightPlanCoordinates_arr[0]["latitude"],flightPlanCoordinates_arr[0]["longitude"]),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
}
var map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
var Colors = ["#FF0000", "#00FF00", "#0000FF", "#FFFFFF", "#000000", "#FFFF00", "#00FFFF", "#FF00FF"];
for (var i = 0; i < flightPlanCoordinates.length; i++)
{
if(jQuery.inArray(i+1,store)===-1)
{
var colour = Colors[i];
var flightPath = new google.maps.Polyline({
path: [flightPlanCoordinates[i], flightPlanCoordinates[i+1]],
geodesic: true,
strokeColor: '#FFFF00',
strokeOpacity: 2.0,
strokeWeight: 10,
map: map
});
}
}
flightPath.setMap(map);
var location = "";
var location_details = "";
var speed="";
for(var i in flightPlanCoordinates_arr)
{
location = flightPlanCoordinates_arr[i]["location"];
location_details = flightPlanCoordinates_arr[i]["location_details"];
speed = flightPlanCoordinates_arr[i]["speed"];
var marker = new google.maps.Marker({
position: new google.maps.LatLng(flightPlanCoordinates_arr[i]["latitude"],flightPlanCoordinates_arr[i]["longitude"]),
map: map
});
marker.setIcon('images/bike.png');
}
new google.maps.event.addListener(flightPath, 'mouseover', function(event) {
var populationOptions = {
strokeColor: '#11C111',
strokeOpacity: 0.8,
strokeWeight: 4,
fillColor: 'transparent',
fillOpacity: 4,
map: map,
center: event.latLng,
position: event.latLng,
radius: 40
};
// Add the circle for this city to the map.
cityCircle = new google.maps.Circle(populationOptions);
attachSecretMessage(marker, contentHtml,map);
});
new google.maps.event.addListener(flightPath, 'mouseout', function(event) {
var marker = new google.maps.Marker({
position: event.latLng,
});
// Add the circle for this city to the map.
cityCircle.setMap(null);
});
}
function attachSecretMessage(marker, contentHtml, map) {
var infowindow = new google.maps.InfoWindow({
position: marker.position,
content: contentHtml
});
google.maps.event.addListener(marker, 'mouseover', function() {
infowindow.open(map);
});
google.maps.event.addListener(marker, 'mouseout', function() {
infowindow.close();
});
}
mapData is a JSON response which brings 'Latitude','Longitude','Speed','State','Location' values.
I have drawn polylines for the Lats and Longs , but the markers are not displayed.And getting this error
TypeError: f is undefined
Your design is not clear to me exactly.
If you want to get marker visible in mouseout event listener than you have to provide map value. For example:
var marker = new google.maps.Marker({
position: event.latLng,
map: map
});
In that case you have to make map global. Currently it is locally defined in function initialize(). So:
var map;
function initialize(flightPlanCoordinates_arr) {
...
map = new google.maps.Map(document.getElementById('map'), mapOptions);
...
}
Additionally, it seems that this for loop
for (var i = 0; i < flightPlanCoordinates.length; i++) {
should be initialized as:
for (var i = 0; i < flightPlanCoordinates.length - 1; i++) {
Update: see example at jsbin. It's best I can get because I do not understand whole logic of some variables checking. If you set prober icon marker will be set. Note: I cannot perform that ajax call so I had to model data.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Google Maps - Multiple markers - 1 InfoWindow problem
I'm making a map where I plot some towns and places.
As you will see, when you click on a marker, you are redirected to the corresponding page. But now I would like to put the link and some other information in an info bubble popover. So, I've edit my code to this:
function setMarkers(map, locations) {
for (var i = 0; i < locations.length; i++) {
var beach = locations[i];
var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
var infobulle = new google.maps.InfoWindow({content: beach[4], position: myLatLng});
var marker = new google.maps.Marker({position: myLatLng, map: map, title: beach[0], zIndex: beach[3], clickable: true, icon: beach[5],});
marker[i] = marker;
google.maps.event.addListener(marker[i], 'click', function() {
infobulle.open(map, marker);
});
}
}
But as you can see here the info bubble stays "blocked" on the last location. I really don't know how to sort this.
I have the same result with this :
function setMarkers(map, locations) {
for (var i = 0; i < locations.length; i++) {
var beach = locations[i];
var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
var infobulle = new google.maps.InfoWindow({content: beach[4]});
var marker = new google.maps.Marker({position: myLatLng, map: map, title: beach[0], zIndex: beach[3], clickable: true, icon: beach[5]});
google.maps.event.addListener(marker, 'click', function() {
infobulle.open(map, marker);
});
}
Last version :
function setMarkers(map, locations) {
for (var i = 0; i < locations.length; i++) {
processBeach(locations[i]);
}
}
function processBeach(beach) {
var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
var infobulle = new google.maps.InfoWindow({content: beach[4]});
var marker = new google.maps.Marker({position: myLatLng, map: map, title: beach[0], zIndex: beach[3], clickable: true, icon: beach[5]});
google.maps.event.addListener(marker, 'click', function() {
infobulle.open(map, marker);
});
}
You are using the marker variable for two different purposes it seems. One is as a single marker, and one as an array of markers. But you don't need an array of markers, if you use closures. Try this:
function setMarkers(map, locations) {
for (var i = 0; i < locations.length; i++) {
(function(beach) {
var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
var infobulle = new google.maps.InfoWindow({content: beach[4], position: myLatLng});
var marker = new google.maps.Marker({position: myLatLng, map: map, title: beach[0], zIndex: beach[3], clickable: true, icon: beach[5]}))
google.maps.event.addListener(marker, 'click', function() {
infobulle.open(map, marker);
});
}(locations[i]));
}
}
By the way you also had a spurious comma at the end of the options array for google.maps.Marker which will cause problems in some browsers.
EDIT
If you don't want to use closures, this is equivalent:
function processBeach(beach) {
var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
var infobulle = new google.maps.InfoWindow({content: beach[4], position: myLatLng});
var marker = new google.maps.Marker({position: myLatLng, map: map, title: beach[0], zIndex: beach[3], clickable: true, icon: beach[5]}))
google.maps.event.addListener(marker, 'click', function() {
infobulle.open(map, marker);
});
}
function setMarkers(map, locations) {
for (var i = 0; i < locations.length; i++) {
processBeach(locations[i]);
}
}
Have a look at my jSFiddle here. The code you are missing is
On Click you need to fetch the current infoWindow from the map and then update it with new information
If you want to keep windows open and close when people want to close then you have to set a toggle kind of variable so each window will be created on click and then when someone click on close it will go away. But i think you only need to complete first part.
The code you should look in my fiddle is from line 120 to 150 which does check for infowindow if it exists and then do open the same window on new marker so it moves from old marker and go to new. if you keep creating new windows the old ones will not close magically.
var map = $(this).gmap3("get"),
infowindow = $(this).gmap3({get:{name:"infowindow"}}); // Get current info window
if (infowindow){ // if infoWindow is there then use it else create new
infowindow.open(map, marker);
infowindow.setContent(context.data.ht);
jQuery("#customPopup").html(context.data.ht);
jQuery("#customPopup").show(500);
} else {
$(this).gmap3({
infowindow:{
anchor:marker,
options:{content: context.data.ht}
}
});
jQuery("#customPopup").html(context.data.ht);
jQuery("#customPopup").show(500);
}