Create marker on polyline from distance - google-maps

I have the following code that draws a polyline between 13 GPS coordinates.The polyline is drawn correctly. I'm trying to put a marker on the distance of 5 KM from the starting point of the polyline. I'm trying to use GetPointAtDistance() from v3_epoly but when I reference it, using
flightPath.GetPointAtDistance(5000);
just before flightPath.setMap(map); but the polyline disappears and no new marker appears. I'm ripping my hair out about why this isn't working, any help would be much appreciated
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>VM 2</title>
<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?sensor=false&libraries=geometry"></script>
<script type="text/javascript" src="scripts/v3_epoly.js"></script>
</head>
<body style="font-family: Arial; font-size: 12px;">
<div style="width: 100%;" id="mapDiv">
<div id="map" style="width: 70%; height: 600px; float: left;margin:0px;color:black;"></div>
<div id="panel" style="width: 30%; float: left;margin:0px;"></div>
</div>
<script type="text/javascript">
var locations = [
{
title: "Point 1",
lat : -0.004259,
lng : 36.96367099999998,
},
{
title: "Point 2",
lat : 0.3606,
lng : 36.782,
},
{
title: "Point 3",
lat : 0.3145033,
lng : 36.9755982,
},
{
title: "Point 4",
lat : 0.2336305,
lng : 37.3166943,
},
{
title: "Point 5",
lat : 0.2253856,
lng : 37.440852,
},
{
title: "Point 6",
lat : 0.0880828,
lng : 38.1899782,
},
{
title: "Point 7",
lat : -0.2356904,
lng : 36.8766403,
},
{
title: "Point 8",
lat : -0.4169027,
lng : 36.6666989,
},
{
title: "Point 9",
lat : -0.3666667,
lng : 36.0833333,
},
{
title: "Point 10",
lat : -1.4065513,
lng : 34.906551,
},
{
title: "Point 11",
lat : -1.3666667,
lng : 36.8333333,
},
{
title: "Point 12",
lat : -2.55143,
lng : 37.79738,
},
{
title: "Point 13",
lat : -3.3951791,
lng : 37.9572584,
},
];
function initialize() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom : 2,
center : new google.maps.LatLng(10, -10),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i].lat, locations[i].lng),
map : map
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(locations[i].title);
infowindow.open(map, marker);
}
})(marker, i));
}
var flightPath = new google.maps.Polyline({
path : locations,
geodesic : true,
strokeColor : '#5589ca',
strokeOpacity: 1.0,
strokeWeight : 2
});
var latlngex = new google.maps.LatLng(-4.0434771,39.6682065);
var titleex = "Test Marker";
createMarker(map,latlngex,titleex);
flightPath.setMap(map);
}
function createMarker(map, latlng, title){
var marker = new google.maps.Marker({
position:latlng,
map:map,
title: title,
icon: 'http://maps.google.com/mapfiles/ms/icons/green-dot.png'
});
}
google.maps.event.addDomListener(window, "load", initialize);
</script>
</body>

I had no luck getting v3_epoly to connect to JSfiddle.
Instead, I used the method from geocodezips implementation and added the function locally:
GetPointAtDistance = function(metres) {
// some awkward special cases
if (metres == 0) return flightPath.getPath().getAt(0);
if (metres < 0) return null;
if (flightPath.getPath().getLength() < 2) return null;
var dist = 0;
var olddist = 0;
for (var i = 1;
(i < flightPath.getPath().getLength() && dist < metres); i++) {
olddist = dist;
dist += google.maps.geometry.spherical.computeDistanceBetween(
flightPath.getPath().getAt(i),
flightPath.getPath().getAt(i - 1)
);
}
if (dist < metres) {
return null;
}
var p1 = flightPath.getPath().getAt(i - 2);
var p2 = flightPath.getPath().getAt(i - 1);
var m = (metres - olddist) / (dist - olddist);
return new google.maps.LatLng(p1.lat() + (p2.lat() - p1.lat()) * m, p1.lng() + (p2.lng() - p1.lng()) * m);
}
and called it using the following:
createMarker(map, GetPointAtDistance(30000), titleex);
And the green marker will appear.
I made some other slight altercation, here is JsFiddle : https://jsfiddle.net/cmjcs5eL/19/

Related

How to make a object back to the start point in java map

I want to make something like bus tracking which go around a polygon who moving 2 meters every second back to the start point. And every second the object(?) point coordinate.
And I don't even know how to start it. Help me please.
The polygon code:
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
zoom: 12,
center: { lat: 0.5164426, lng: 101,4574499 },
mapTypeId: "terrain",
});
const triangleCoords = [
{ lat: 0.5022181713704478, lng: 101.41882830662435 },
{ lat: 0.4975231087415325, lng: 101.39433139688956 },
{ lat: 0.5103834896305101, lng: 101.39412725597509 },
{ lat: 0.5169157367830446, lng: 101.39923077883651 },
{ lat: 0.5350835135799168, lng: 101.4035177380401 },
{ lat: 0.5348793815517918, lng: 101.41984901119662 },
];
const bermudaTriangle = new google.maps.Polygon({
paths: triangleCoords,
strokeColor: "#0000FF",
strokeOpacity: 1,
strokeWeight: 2,
fillColor: "#FF6633",
fillOpacity: 0.35,
});
bermudaTriangle.setMap(map);
bermudaTriangle.addListener("click", showArrays);
infoWindow = new google.maps.InfoWindow();
Basically how to make a bus from lat: 0.5022181713704478, lng: 101.41882830662435 back to lat: 0.5022181713704478, lng: 101.41882830662435 dramatically
What I expected: http://www.geocodezip.com/v3_animate_marker_directions.html
but it has 6 point stated and moving endlessly
You have several issues with the posted code:
no : after lng on the map center: `
center: { lat: 0.5164426, lng 101,4574499 },
should be:
center: { lat: 0.5164426, lng: 101,4574499 },
no comma after fillColor: "#FF6633" in the PolygonOptions
in the PolygonOptions panths should be paths
to be consistent with my example, you need a Polyline (rather than a Polygon), which means you need to add the last point to complete the path:
const triangleCoords = [{
lat: 0.5022181713704478,
lng: 101.41882830662435
},
{
lat: 0.4975231087415325,
lng: 101.39433139688956
},
{
lat: 0.5103834896305101,
lng: 101.39412725597509
},
{
lat: 0.5169157367830446,
lng: 101.39923077883651
},
{
lat: 0.5350835135799168,
lng: 101.4035177380401
},
{
lat: 0.5348793815517918,
lng: 101.41984901119662
},
{ // duplicate of first point
lat: 0.5022181713704478,
lng: 101.41882830662435
},
];
proof of concept fiddle
To prevent the center of the map from changing, remove the code that changes the center (one instance of map.setCenter, two instances of map.panTo):
fiddle where map center not modified
To keep the marker circling around the loop, change the "end" condition to restart the animation, by calling animate(0):
function animate(d) {
if (d > eol) {
map.panTo(polyline.getPath().getAt(polyline.getPath().getLength() - 1));
marker.setPosition(polyline.getPath().getAt(polyline.getPath().getLength() - 1));
// continuous loop
animate(0);
return;
}
live example
code snippet:
var polyline, marker;
function initMap() {
addEpolyFunc();
map = new google.maps.Map(document.getElementById("map"), {
zoom: 12,
center: {
lat: 0.5164426,
lng: 101.4574499
},
mapTypeId: "terrain",
});
const triangleCoords = [{
lat: 0.5022181713704478,
lng: 101.41882830662435
},
{
lat: 0.4975231087415325,
lng: 101.39433139688956
},
{
lat: 0.5103834896305101,
lng: 101.39412725597509
},
{
lat: 0.5169157367830446,
lng: 101.39923077883651
},
{
lat: 0.5350835135799168,
lng: 101.4035177380401
},
{
lat: 0.5348793815517918,
lng: 101.41984901119662
},
{
lat: 0.5022181713704478,
lng: 101.41882830662435
},
];
const bermudaTriangle = new google.maps.Polygon({
paths: triangleCoords,
strokeColor: "#0000FF",
strokeOpacity: 1,
strokeWeight: 2,
fillColor: "#FF6633",
fillOpacity: 0.35,
});
bermudaTriangle.setMap(map);
infoWindow = new google.maps.InfoWindow();
polyline = new google.maps.Polyline({
// map: map,
path: triangleCoords,
strokeColor: "#0000FF",
strokeOpacity: 1,
strokeWeight: 2,
});
marker = new google.maps.Marker({
position: polyline.getPath().getAt(0),
map: map
})
startAnimation();
}
var step = 50; // 5; // metres
var tick = 100; // milliseconds
var eol;
var k = 0;
var stepnum = 0;
var speed = "";
var lastVertex = 1;
//=============== animation functions ======================
function updatePoly(d) {
// Spawn a new polyline every 20 vertices, because updating a 100-vertex poly is too slow
if (poly2.getPath().getLength() > 20) {
poly2 = new google.maps.Polyline([polyline.getPath().getAt(lastVertex - 1)]);
}
if (polyline.GetIndexAtDistance(d) < lastVertex + 2) {
if (poly2.getPath().getLength() > 1) {
poly2.getPath().removeAt(poly2.getPath().getLength() - 1)
}
poly2.getPath().insertAt(poly2.getPath().getLength(), polyline.GetPointAtDistance(d));
} else {
poly2.getPath().insertAt(poly2.getPath().getLength(), polyline.getPath().getAt(polyline.getPath().getLength() - 1));
}
}
function animate(d) {
if (d > eol) {
map.panTo(polyline.getPath().getAt(polyline.getPath().getLength() - 1));
marker.setPosition(polyline.getPath().getAt(polyline.getPath().getLength() - 1));
// continuous loop
animate(0);
return;
}
var p = polyline.GetPointAtDistance(d);
map.panTo(p);
marker.setPosition(p);
updatePoly(d);
timerHandle = setTimeout("animate(" + (d + step) + ")", tick);
}
function startAnimation() {
eol = google.maps.geometry.spherical.computeLength(polyline.getPath());
map.setCenter(polyline.getPath().getAt(0));
poly2 = new google.maps.Polyline({
path: [polyline.getPath().getAt(0)],
strokeColor: "#0000FF",
strokeWeight: 10
});
setTimeout("animate(50)", 2000); // Allow time for the initial map display
}
function addEpolyFunc() {
//=============== ~animation funcitons =====================
// from epoly_v3.js
// modified to use geometry library for length of line segments
// === A method which returns the Vertex number at a given distance along the path ===
// === Returns null if the path is shorter than the specified distance ===
google.maps.Polyline.prototype.GetIndexAtDistance = function(metres) {
// some awkward special cases
if (metres == 0) return this.getPath().getAt(0);
if (metres < 0) return null;
var dist = 0;
var olddist = 0;
for (var i = 1;
(i < this.getPath().getLength() && dist < metres); i++) {
olddist = dist;
dist += google.maps.geometry.spherical.computeDistanceBetween(this.getPath().getAt(i), this.getPath().getAt(i - 1));
}
if (dist < metres) {
return null;
}
return i;
}
// === A method which returns a GLatLng of a point a given distance along the path ===
// === Returns null if the path is shorter than the specified distance ===
google.maps.Polyline.prototype.GetPointAtDistance = function(metres) {
// some awkward special cases
if (metres == 0) return this.getPath().getAt(0);
if (metres < 0) return null;
if (this.getPath().getLength() < 2) return null;
var dist = 0;
var olddist = 0;
for (var i = 1;
(i < this.getPath().getLength() && dist < metres); i++) {
olddist = dist;
dist += google.maps.geometry.spherical.computeDistanceBetween(this.getPath().getAt(i), this.getPath().getAt(i - 1));
}
if (dist < metres) {
return null;
}
var p1 = this.getPath().getAt(i - 2);
var p2 = this.getPath().getAt(i - 1);
var m = (metres - olddist) / (dist - olddist);
return new google.maps.LatLng(p1.lat() + (p2.lat() - p1.lat()) * m, p1.lng() + (p2.lng() - p1.lng()) * m);
}
// === A method which returns the length of a path in metres ===
google.maps.Polyline.prototype.Distance = function() {
var dist = 0;
for (var i = 1; i < this.getPath().getLength(); i++) {
dist += google.maps.geometry.spherical.computeDistanceBetween(this.getPath().getAt(i), this.getPath().getAt(i - 1));
}
return dist;
}
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>Simple Polygon</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=geometry&v=weekly" defer></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<div id="map"></div>
</body>
</html>

Route inside marker radius Google Maps

I need your help
I need to know if in some point my route (A->B) is inside my Marker(C) radius
Is there a way to get some true or false of this event?
The idea of this its make something like Uber Pool algorythm or something close to that
JS:
function initMap() {
var pointA = new google.maps.LatLng(51.7519, -1.2578),
pointB = new google.maps.LatLng(50.8429, -0.1313),
pointC = new google.maps.LatLng(51.2029, -0.1403),
myOptions = {
zoom: 7,
center: pointA
},
map = new google.maps.Map(document.getElementById('map-canvas'), myOptions),
// Instantiate a directions service.
directionsService = new google.maps.DirectionsService,
directionsDisplay = new google.maps.DirectionsRenderer({
map: map
}),
markerA = new google.maps.Marker({
position: pointA,
title: "point A",
label: "A",
map: map
}),
markerB = new google.maps.Marker({
position: pointB,
title: "point B",
label: "B",
map: map
}),
markerC = new google.maps.Marker({
position: pointC,
title: "point C",
label: "C",
map: map
});
var circle = new google.maps.Circle({
map: map,
radius: 1000, // 10 miles in metres
fillColor: '#AA0000'
});
circle.bindTo('center', markerC, 'position');
// get route from A to B
calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointB);
}
function calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointB) {
directionsService.route({
origin: pointA,
destination: pointB,
avoidTolls: true,
avoidHighways: false,
travelMode: google.maps.TravelMode.DRIVING
}, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
initMap();
HTML
<div id="map-canvas"></div>
CSS
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map-canvas {
height: 100%;
width: 100%;
}
HereĀ“s the fiddle
Tks a lot
Process through all the points in the returned directions polyline, check if any of them are in the circle.
// convert the directions response to polylines
renderDirectionsPolylines(response);
// check to see if any of the points from the route are in the circle
for (var i = 0; i < polylines.length; i++) {
for (var j = 0; j < polylines[i].getPath().getLength(); j++) {
if (google.maps.geometry.spherical.computeDistanceBetween(polylines[i].getPath().getAt(j), circle.getCenter()) < circle.getRadius()) {
console.log("route intersects circle at:" + polylines[i].getPath().getAt(j).toUrlValue(6));
}
}
}
proof of concept fiddle
code snippet:
var map;
function initMap() {
var pointA = new google.maps.LatLng(51.7519, -1.2578),
pointB = new google.maps.LatLng(50.8429, -0.1313),
pointC = new google.maps.LatLng(51.2029, -0.1403),
myOptions = {
zoom: 7,
center: pointA
},
map = new google.maps.Map(document.getElementById('map-canvas'), myOptions),
// Instantiate a directions service.
directionsService = new google.maps.DirectionsService,
directionsDisplay = new google.maps.DirectionsRenderer({
map: map,
preserveViewport: true
}),
markerA = new google.maps.Marker({
position: pointA,
title: "point A",
label: "A",
map: map
}),
markerB = new google.maps.Marker({
position: pointB,
title: "point B",
label: "B",
map: map
}),
markerC = new google.maps.Marker({
position: pointC,
title: "point C",
label: "C",
map: map
});
var circle = new google.maps.Circle({
map: map,
radius: 1000, // 10 miles in metres
fillColor: '#AA0000'
});
circle.bindTo('center', markerC, 'position');
// get route from A to B
calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointB, circle);
}
function calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointB, circle) {
directionsService.route({
origin: pointA,
destination: pointB,
avoidTolls: true,
avoidHighways: false,
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
renderDirectionsPolylines(response);
console.log("polylines=" + polylines.length);
for (var i = 0; i < polylines.length; i++) {
for (var j = 0; j < polylines[i].getPath().getLength(); j++) {
if (google.maps.geometry.spherical.computeDistanceBetween(polylines[i].getPath().getAt(j), circle.getCenter()) < circle.getRadius()) {
console.log("route intersects circle at:" + polylines[i].getPath().getAt(j).toUrlValue(6));
var mark = new google.maps.Marker({
map: circle.getMap(),
position: polylines[i].getPath().getAt(j),
icon: {
url: "https://maps.gstatic.com/intl/en_us/mapfiles/markers2/measle.png",
size: new google.maps.Size(7, 7),
anchor: new google.maps.Point(3.5, 3.5)
}
});
circle.getMap().fitBounds(circle.getBounds());
// document.getElementById('result').innerHTML += "route intersects circle at:"+polylines[i].getPath().getAt(j).toUrlValue(6)+"<br>";
}
}
}
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
var polylineOptions = {
strokeColor: '#C83939',
strokeOpacity: 1,
strokeWeight: 4
};
var polylines = [];
function renderDirectionsPolylines(response) {
for (var i = 0; i < polylines.length; i++) {
polylines[i].setMap(null);
}
var legs = response.routes[0].legs;
for (i = 0; i < legs.length; i++) {
var steps = legs[i].steps;
for (j = 0; j < steps.length; j++) {
var nextSegment = steps[j].path;
var stepPolyline = new google.maps.Polyline(polylineOptions);
for (k = 0; k < nextSegment.length; k++) {
stepPolyline.getPath().push(nextSegment[k]);
}
polylines.push(stepPolyline);
stepPolyline.setMap(map);
// route click listeners, different one on each step
google.maps.event.addListener(stepPolyline, 'click', function(evt) {
infowindow.setContent("you clicked on the route<br>" + evt.latLng.toUrlValue(6));
infowindow.setPosition(evt.latLng);
infowindow.open(map);
})
}
}
}
initMap();
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map-canvas {
height: 100%;
width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
<div id="result"></div>
<div id="map-canvas"></div>

google map api remove straight lines [duplicate]

This question already has an answer here:
An issue while showing a path on Google Maps
(1 answer)
Closed 6 years ago.
I'm developing a MVC app using google map API.
There are 4 or more coordinates in my program. According to that I need to draw road path. This is my code so far.
<div id="dvMap" style="width: 500px; height: 500px">
</div>
#section scripts
{
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyBZxYACsC1qz9gticRd4mbki9Tes9qexdw&sensor=false"></script>
<script type="text/javascript">
var markers = [
{
"title": 'Canberra',
"lat": '-35.2809',
"lng": '149.1300',
"description": ''
},
{
"title": 'Sydny',
"lat": '-33.8688',
"lng": '151.2093',
"description": ''
},
{
"title": 'Tamworth',
"lat": '-31.0927',
"lng": '150.9320',
"description": ''
}
,
{
"title": 'Brisbane',
"lat": '-27.465895',
"lng": '153.019519',
"description": ''
}
];
window.onload = function () {
var mapOptions = {
center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
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();
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
});
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();
//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.setPath(path);
service.route({
origin: src,
destination: des,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function (result, status) {
if (status == google.maps.DirectionsStatus.OK) {
console.log('len ' + result.routes[0].overview_path.length)
for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
path.push(result.routes[0].overview_path[i]);
}
}
});
}
}
}
</script>
}
The problem is the map is shown straight lines as well.
I need to remove straight lines from the map (should keep lines draw on road path) and what's wrong in my code? In addition, Markers should show only for starting point and destination point. But all points are shown as markers. So how to do it...? Please give me a direction for doing it....
At the beginning of your script you're drawing markers on the map. To avoid that comment out the line map: map,
var marker = new google.maps.Marker({
position: myLatlng,
// map: map,
title: data.title
});
To remove the straight lines from the map:
comment out the line
//poly.setPath(path);
You need to use a DirectionsRenderer to show routes on the map once the routes are returned by the directionsService.
Define a function to render the computed routes
function renderDirections(result) {
var directionsRenderer = new google.maps.DirectionsRenderer;
directionsRenderer.setMap(map);
directionsRenderer.setDirections(result);
};
Add the rendering to the callback function of the directionsService
directionsService.route({
origin: src,
destination: des,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function(result, status) {
// if route is computed successfully, render it on map
if (status == google.maps.DirectionsStatus.OK) {
console.log('len ' + result.routes[0].overview_path.length);
renderDirections(result);
} else {
console.log("Error: ", status);
}
});
The issue here is that you're trying to display multiple routes on your map, check this question for details.
Hope this helps.

How to Zoom In further in google map to show markers clearly

I have got four markers which will be shown when i zoom in till the last .
The issue i am facing is that the markers one and four are overlapping with each other , and i cannot zoom zoom in further to click on them ?
Is there any solution for this without using Marker cluster??
some part of my code
function addMarker(response, lator, lonor, infowindow) {
if (response.length > 0) {
var global_markers = [];
for (var i = 0; i < response.length; i++) {
var lat = parseFloat(response[i].latitude);
var lng = parseFloat(response[i].longititude);
var dealername = response[i].name;
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),
map: map,
title: "Dealer name: " + dealername,
icon: 'http://maps.google.com/mapfiles/marker.png'
});
global_markers[i] = marker;
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
}
}
}
This is my fiddle
http://jsfiddle.net/3VXTL/13/
Please let me know how to resolve this ??
One option is to make the markers smaller (use the "measle" little red do).
updated fiddle
code snippet:
var response = [{
"longititude": "78.377665",
"latitude": "17.439669",
"name": "one"
}, {
"longititude": "78.377617",
"latitude": "17.439692",
"name": "two"
}, {
"longititude": "78.377644",
"latitude": "17.439674",
"name": "three"
}, {
"longititude": "78.377665",
"latitude": "17.439667",
"name": "four"
}]
initializeCalllater(18.1124372, 79.01929969999999, response);
function initializeCalllater(lator, lonor, response) {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(lator, lonor);
var myOptions = {
zoom: 7,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE
},
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
google.maps.event.trigger(map, 'resize');
map.setCenter(new google.maps.LatLng(lator, lonor));
var infowindow = new google.maps.InfoWindow({});
addMarker(response, lator, lonor, infowindow);
}
function addMarker(response, lator, lonor, infowindow) {
if (response.length > 0) {
var global_markers = [];
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < response.length; i++) {
var lat = parseFloat(response[i].latitude);
var lng = parseFloat(response[i].longititude);
var dealername = response[i].name;
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),
map: map,
title: "Dealer name: " + dealername,
icon: {
url: "https://maps.gstatic.com/intl/en_us/mapfiles/markers2/measle.png",
size: new google.maps.Size(7, 7),
anchor: new google.maps.Point(3.5, 3.5)
}
});
bounds.extend(marker.getPosition());
global_markers[i] = marker;
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
}
map.fitBounds(bounds);
}
}
body,
html,
#map_canvas {
height: 100%;
width: 100%;
}
<script src="http://maps.google.com/maps/api/js"></script>
<div id="map_canvas" "></div>
If that is not enough, you could change the zIndex of the markers that overlap when you click on one of them (like this question: allow user to move marker position back (z-index?) in google maps custom map).

Using custom pin icon in Google maps only shows first location in loop

I've tried a number of things to try resolve this but I can't seem to find a solution. The problem is that only the first location is added to my map and the other places are left out. When I remove the custom pin icon, all the locations are added correctly. The line that seems to affect this is:
icon: iconType[place.icon]
As I said when I remove this line everything works as expected. What am I doing wrong?
Code below
I have a number of places defined in an object like so:
var data = [
{
"name" : "Hotel A",
"latlng" : new google.maps.LatLng(-33.636784,19.098212),
"icon" : "venue",
"desc" : "This is the venue",
},
...
];
Icons are defined like this:
iconType = {
'oneStar' : 'mapimages/lodging_1star.png',
'twoStar' : 'mapimages/lodging_2star.png',
...
};
I place my locations on the map using a for loop, looping through the data variable like so:
var bounds = new google.maps.LatLngBounds();
var map;
var infowindow = new google.maps.InfoWindow({ maxWidth: 300 });
var marker;
function initialize() {
// init map
var venueLatlng = new google.maps.LatLng(-33.636784,19.098212);
var mapOptions = {
zoom: 12,
center: venueLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
for (var i = 0; i < data.length; i++) {
createMarker(data[i]);
}
map.fitBounds(bounds);
}
function createMarker(place) {
bounds.extend(place.latlng);
marker = new google.maps.Marker({
position: place.latlng,
title: place.name,
map: map,
icon: iconType[place.icon]
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.desc);
infowindow.open(map, marker);
});
}
This works for me (I don't have your icons, so I linked to public ones on Google's server):
<script>
var map;
var data = [
{
"name" : "Venue A",
"latlng" : new google.maps.LatLng(-33.636784,19.098212),
"icon" : "venue",
"desc" : "This is the venue",
},
{
"name" : "Hotel A",
"latlng" : new google.maps.LatLng(-33.6,19.0),
"icon" : "oneStar",
"desc" : "one star",
},
{
"name" : "Hotel B",
"latlng" : new google.maps.LatLng(-33.4,19.0),
"icon" : "twoStar",
"desc" : "two star",
}
];
iconType = {
'oneStar' : 'http://maps.google.com/mapfiles/ms/icons/blue.png',
'twoStar' : 'http://maps.google.com/mapfiles/ms/icons/red.png',
'venue' : 'http://maps.google.com/mapfiles/ms/icons/yellow.png'
};
var bounds = new google.maps.LatLngBounds();
var map;
var infowindow = new google.maps.InfoWindow({ maxWidth: 300 });
var marker;
function initialize() {
// init map
var venueLatlng = new google.maps.LatLng(-33.636784,19.098212);
var mapOptions = {
zoom: 12,
center: venueLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
for (var i = 0; i < data.length; i++) {
createMarker(data[i]);
}
map.fitBounds(bounds);
}
function createMarker(place) {
bounds.extend(place.latlng);
var marker = new google.maps.Marker({
position: place.latlng,
title: place.name,
map: map,
icon: iconType[place.icon]
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent('<b>'+place.name+'</b><br>'+place.desc);
infowindow.open(map, marker);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>