Google Maps: Select previous Marker on Polyline - javascript

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.

Related

Google Maps modify/remove populated polylines

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.

Unexplained extra Polyline drawn - Google Maps API v3

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

Marker new postion created but old is also showing in ajax google map

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.

Markers not shown on Multiple Polylines

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.

google maps clustering marker

i am trying to add clustering on my map, the code i am using is working fine but there is no clustring on it and can't figure out how should i add the cluster to this code.
(function (namespace, $, undefined) {
// map the namespace to that
var that = namespace;
var markers = [];
var dealers = [];
var googleMap;
var tmpDealer = "";
function AddMarkers(aar, map, show) {
if (aar.length > 0) {
var image = '/Files/Templates/Designs/Mobler/images/MapMarker.png';
for (var i = 0; i < aar.length; i++) {
markers.push( new google.maps.Marker({
position: new google.maps.LatLng(parseFloat( aar[i].Latitude),parseFloat(aar[i].Longitude)),
map: map,
title: aar[i].Name,
icon: image,
DealerId: aar[i].DealerId,
DealerPage: aar[i].Area
}));
}
for (var i = 0; i < markers.length; i++) {
if (show) {
google.maps.event.addListener(markers[i], "click", function () {
tmpDealer = this.DealerPage;
MoblerLandingPage.SetCookie("/Default.aspx" + tmpDealer, false);
MoblerLandingPage.SetAreaName("/Default.aspx?AreaID=" + this.DealerPage, function() {
setTimeout(function() {
var area = $.cookie("MoblerAreaName");
document.location = "http://" + document.domain + "/" + area;
}, 250);
});
});
} else {
google.maps.event.addListener(markers[i], "click", that.onMarkerClick)
}
}
}
}
var InfoBoxOptions2 = {
content: ""
, disableAutoPan: false
, maxWidth: 0
, pixelOffset: new google.maps.Size(-75, -5)
, zIndex: null
, boxClass: "DealerMapInfoBox"
, closeBoxMargin: "5px"
, closeBoxURL: "/Files/Templates/Designs/SmagOgBehag/images/infoBoxClose.png"
, infoBoxClearance: new google.maps.Size(1, 1)
, isHidden: false
, pane: "floatPane"
, enableEventPropagation: false
, alignBottom : true
};
var infoBox2 = new InfoBox(InfoBoxOptions2);
that.Initialize = function(mapId, dealerArray, show){
dealers = dealerArray;
var mapOptions = {
center: new google.maps.LatLng(56.22, 11.32),
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
if(!show){
var mapOptions = {
center: new google.maps.LatLng(56.22, 11.32),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
}
googleMap = new google.maps.Map(document.getElementById(mapId), mapOptions);
if(dealerArray.constructor === Array && dealerArray.length > 0){
AddMarkers(dealers, googleMap, show);
}
if(!show){
google.maps.event.addListener(googleMap, 'click', function () {
infoBox2.close();
});
}
}
that.onMarkerClick = function(){
var marker = this;
infoBox2.content_ = $('#Dealer' + marker.DealerId + ' li a').html();
infoBox2.open(marker.map, marker);
}
that.ShowDealerOnMap = function(dealerId) {
for (var i = 0; i < markers.length; i++) {
if (markers[i].DealerId == dealerId) {
var marker = markers[i];
marker.map.setZoom(15);
marker.map.panTo(marker.getPosition())
infoBox2.content_ = $('#Dealer' + marker.DealerId).html()
infoBox2.open(marker.map, marker);
}
}
}
Did you take a look to this documentation ? You can see a working sample to use MarkerClusterer
//Create your map
var center = new google.maps.LatLng(37.4419, -122.1419);
var options = {
'zoom': 13,
'center': center,
'mapTypeId': google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), options);
//Create the clusterer and its options
var mcOptions = {gridSize: 50, maxZoom: 15};
var markers = [...]; // Create the markers you want to add and collect them into a array.
//Add the clusterer to the map, and the markers to the clusterer.
var mc = new MarkerClusterer(map, markers, mcOptions);
Please note that if you don't have a lot of markers, you'll have to change some options in order to see the clusterer working. Change the maxZoom where the clusterer works, and the size of the grid ( gridSize option).
For a complete list of all options, please refer to this document
See this:
http://www.appelsiini.net/2008/introduction-to-marker-clustering-with-google-maps
You can make clusters, rectangle based or square based.

Categories

Resources