jquery repeatly attributes - google map - javascript

$(document).ready(function() {
var markers = [
{
"lat": '51.508742',
"lng": '-0.12085'
}
];
window.onload = function () {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
mapTypeId: google.maps.MapTypeId.ROADMAP,
fullscreenControl: true,
styles: [{"featureType":"administrative","elementType":"labels.text.fill","stylers":[{"color":"#6195a0"}]},{"featureType":"landscape","elementType":"all","stylers":[{"color":"#f2f2f2"}]},{"featureType":"landscape","elementType":"geometry.fill","stylers":[{"color":"#ffffff"}]},{"featureType":"poi","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"poi.park","elementType":"geometry.fill","stylers":[{"color":"#e6f3d6"},{"visibility":"on"}]},{"featureType":"road","elementType":"all","stylers":[{"saturation":-100},{"lightness":45},{"visibility":"simplified"}]},{"featureType":"road.highway","elementType":"all","stylers":[{"visibility":"simplified"}]},{"featureType":"road.highway","elementType":"geometry.fill","stylers":[{"color":"#f4d2c5"},{"visibility":"simplified"}]},{"featureType":"road.highway","elementType":"labels.text","stylers":[{"color":"#4e4e4e"}]},{"featureType":"road.arterial","elementType":"geometry.fill","stylers":[{"color":"#f4f4f4"}]},{"featureType":"road.arterial","elementType":"labels.text.fill","stylers":[{"color":"#787878"}]},{"featureType":"road.arterial","elementType":"labels.icon","stylers":[{"visibility":"off"}]},{"featureType":"transit","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"water","elementType":"all","stylers":[{"color":"#eaf6f8"},{"visibility":"on"}]},{"featureType":"water","elementType":"geometry.fill","stylers":[{"color":"#eaf6f8"}]}]
};
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
}
$("#tab_id_1 li").click(function() {
event.preventDefault();
var data_lat1 = $(this).attr('data-lat-1');
var data_lng1 = $(this).attr('data-lng-1');
var data_lat2 = $(this).attr('data-lat-2');
var data_lng2 = $(this).attr('data-lng-2');
map(data_lat1,data_lng1,data_lat2,data_lng2);
});
function map(data_lat1,data_lng1,data_lat2,data_lng2){
$("#tab_id_1 li").on("click",function(){
var markers = [
{
"lat": ''+ data_lat1 +'',
"lng": ''+ data_lng1 +''
}
,
{
"lat": ''+ data_lat2 +'',
"lng": ''+ data_lng2 +''
}
];
console.log(markers);
var mapOptions = {
zoom: 7,
center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
mapTypeId: google.maps.MapTypeId.ROADMAP,
fullscreenControl: true,
styles: [{"featureType":"administrative","elementType":"labels.text.fill","stylers":[{"color":"#6195a0"}]},{"featureType":"landscape","elementType":"all","stylers":[{"color":"#f2f2f2"}]},{"featureType":"landscape","elementType":"geometry.fill","stylers":[{"color":"#ffffff"}]},{"featureType":"poi","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"poi.park","elementType":"geometry.fill","stylers":[{"color":"#e6f3d6"},{"visibility":"on"}]},{"featureType":"road","elementType":"all","stylers":[{"saturation":-100},{"lightness":45},{"visibility":"simplified"}]},{"featureType":"road.highway","elementType":"all","stylers":[{"visibility":"simplified"}]},{"featureType":"road.highway","elementType":"geometry.fill","stylers":[{"color":"#f4d2c5"},{"visibility":"simplified"}]},{"featureType":"road.highway","elementType":"labels.text","stylers":[{"color":"#4e4e4e"}]},{"featureType":"road.arterial","elementType":"geometry.fill","stylers":[{"color":"#f4f4f4"}]},{"featureType":"road.arterial","elementType":"labels.text.fill","stylers":[{"color":"#787878"}]},{"featureType":"road.arterial","elementType":"labels.icon","stylers":[{"visibility":"off"}]},{"featureType":"transit","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"water","elementType":"all","stylers":[{"color":"#eaf6f8"},{"visibility":"on"}]},{"featureType":"water","elementType":"geometry.fill","stylers":[{"color":"#eaf6f8"}]}]
};
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,
icon: "marker-icon.png"
});
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****************//
//Intialize the Path Array
var path = new google.maps.MVCArray();
//Intialize the Direction Service
var service = new google.maps.DirectionsService();
//Set the Path Stroke Color
var poly = new google.maps.Polyline({ map: map, strokeColor: '#f09c00', strokeOpacity: 1.0, strokeWeight: 5 });
//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) {
for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
path.push(result.routes[0].overview_path[i]);
}
}
});
}
}
});
}
});
Help please! when the first time is pushed, nothing happens, then when you press again on one of the "li" the coordinates are sent with 1 array, the third time when the push is sent 2 arrays, the fourth time is sent 3 arrays, the fifth time is sent 4 arrays, how can I solve the problem, when I'm pushing to send only 1 array, sorry for my bad english.
<ul id="tab_id_1" class="uk-nestable" data-uk-nestable="{group:'my-group', maxDepth:1}">
<li data-lat-1="51.5501741" data-lng-1="-0.003371000000015556" data-lat-2="-33.88081" data-lng-2="-33.88081" class="uk-nestable-item">
<input type="hidden" name="id_1[]" value="9">
<div class="uk-nestable-panel">
<div>
<div class="table dd_table">
<div>Sat30</div>
<div>Nr.Q767</div>
<div>DELIVERY</div>
<div>754876</div>
<div><i class="fa fa-eye"></i></div>
</div>
</div>
</div>
</li>
<li data-lat-1="48.57340529999999" data-lng-1="7.752111300000024" data-lat-2="51.5111922" data-lng-2="51.5111922" class="uk-nestable-item">
<input type="hidden" name="id_1[]" value="7">
<div class="uk-nestable-panel">
<div>
<div class="table dd_table">
<div>Sat30</div>
<div>Nr.W996</div>
<div>DELIVERY</div>
<div>5365-64</div>
<div><i class="fa fa-eye"></i></div>
</div>
</div>
</div>
</li>
<li data-lat-1="48.57340529999999" data-lng-1="7.752111300000024" data-lat-2="52.19173" data-lng-2="52.19173" class="uk-nestable-item">
<input type="hidden" name="id_1[]" value="11">
<div class="uk-nestable-panel">
<div>
<div class="table dd_table">
<div>Sat30</div>
<div>Nr.J765</div>
<div>PICK-UP/DELIVERY</div>
<div>MD-2038/3811-558</div>
<div><i class="fa fa-eye"></i></div>
</div>
</div>
</div>
</li>
</ul>

Please remove the
$("#tab_id_1 li").on("click",function(){
re declaration inside the map function..
That should solve your problem.

Related

How draw rout between markers

I'm facing a problem with google map, the problem is,when i draw rout between markers it duplicated heres the image :
enter image description here
heres the makers:
var markers=[{"longitude":"-5.808954951287861","latitude":"35.77107409886168","deviceTime":"2017-03-29T14:02:36.000+0000"},
{"longitude":"-5.807401662705262","latitude":"35.77029143851354","deviceTime":"2017-03-29T14:05:36.000+0000"},
{"longitude":"-5.794769662196012","latitude":"35.77169804990058","deviceTime":"2017-03-29T14:08:36.000+0000"},
{"longitude":"-5.784207185242776","latitude":"35.76541442176138","deviceTime":"2017-03-29T14:11:36.000+0000"},
{"longitude":"-5.78417853735302","latitude":"35.76539666006973","deviceTime":"2017-03-29T14:14:36.000+0000"},
{"longitude":"-5.784050767764706","latitude":"35.76528034963732","deviceTime":"2017-03-29T14:15:52.000+0000"}];
heres the function :
storyboard.drawTrajet=function(markers){
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var labelIndex = 0;
var mapOptions = {
center: new google.maps.LatLng(markers[0].latitude, markers[0].longitude),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), 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];
alert(markers.length);
var myLatlng = new google.maps.LatLng(data.latitude, data.longitude);
lat_lng.push(myLatlng);
var marker = new google.maps.Marker({
//icon: icons['info'].icon,
label: labels[labelIndex++ % labels.length],
position: myLatlng,
map: map
//title: 'data.title'
});
//path[z].push(marker.getPosition());
latlngbounds.extend(marker.position);
(function (marker, data) {
google.maps.event.addListener(marker, "mouseover", function (e) {
storyboard.geocodeLatLng($scope.geocoder , map, $scope.infoWindow,data.latitude,data.longitude, false,false);
//alert( $scope.MyPos);
infoWindow.setContent('<div ><i class="fa fa-calendar" aria-hidden="true"></i> '+$filter('date')(data.deviceTime, "HH:mm:ss")
+' '+'<i class="glyphicon glyphicon-bookmark" aria-hidden="true"></i>'+$scope.MyPos
+'<div>'
+'<i class="glyphicon glyphicon-map-marker" aria-hidden="true"></i>'+data.latitude+' '
+'<i class="glyphicon glyphicon-map-marker" aria-hidden="true"></i>'+data.longitude
+'</div>'
+'</div>');
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++) {
//alert("sss");
if ((i + 1) < lat_lng.length) {
var src = lat_lng[i];
//src.setMap(null);
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) {
for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
// alert("sssscvvvvvvs");
path.push(result.routes[0].overview_path[i]);
}
}
});
}
}
}
can anyone help please to resolve this problem??
I Think you should use Waypoints for this case. please see example from this.
https://developers.google.com/maps/documentation/javascript/directions#Waypoints

Radius ignored google maps API

I would like to see points of interest within recover from a slider but I feel that the property radius is not taken into account.
When I try to change the value , I see the change, but it is not a good result.
Radius is in meters ?
Can you help me?
thank you in advance
var radius = 50;
$(document).ready(function(){
$('#range-input').on('change', function(evt, range) {
radius = $(this).val();
$('#range-output').val($(this).val() + "m");
});
});
var infowindow;
var latU;
var lngU;
var distance;
var motCle;
function initMap() {
var mapOptions = {
zoom:12,
scaleControl: true,
streetViewControl: true,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL,
position: google.maps.ControlPosition.RIGHT_CENTER
},
mapTypeId: google.maps.MapTypeId.ROADMAP
}
geocoder = new google.maps.Geocoder();
infowindow = new google.maps.InfoWindow();
if (navigator.geolocation)
navigator.geolocation.getCurrentPosition(successCallback,
null,
{enableHighAccuracy:true});
else
alert("Votre navigateur ne prend pas en compte la géolocalisation, activez la localisation et réessayer");
function successCallback(position){
var distance = radius+'m';
var motCle = $('#motCle').val;
latU = position.coords.latitude ;
lngU = position.coords.longitude;
map.panTo(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
var myLatLng = new google.maps.LatLng(latU, lngU);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
map: map,
name: 'Vous êtes ici',
title: 'Vous êtes ici'
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(marker.name);
infowindow.open(map, this);
});
var requestNearby = {
location: myLatLng, //Paramètre de l'endroit ou se trouve la personne
radius: distance,
types: ['shopping_mall', 'grocery_or_supermarket'],
openNow: true
};
service = new google.maps.places.PlacesService(map);
service.nearbySearch(requestNearby, callbackNearby);
function callbackNearby(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}}
map = new google.maps.Map(document.getElementById("map"), mapOptions);
}
$('#searchform').submit(function(e){
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
//alert('sa marche !');
e.preventDefault();
var myLatLng;
console.log(radius);
$.ajax({
method : $(this).attr('method'),
url : $(this).attr('action'),
data : $(this).serialize(),
dataType: 'json'
}).done(function(data){
if(data.success){
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var latU = position.coords.latitude;
var lngU = position.coords.longitude;
myLatLng = new google.maps.LatLng(latU, lngU);
console.log(myLatLng);
serviceSearch = new google.maps.places.PlacesService(map);
var requestText = {
location: myLatLng,
radius: radius,
query: data['message'],
openNow: true
};
serviceSearch.textSearch(requestText, callbackText);
function callbackText(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
createMarker(results[i]);
}
}
}
});
}
} else {
alert('sa ne fonctionne pas correctement!');
}
});
return false;
});
<div class="row">
<div class="col-xs-6">
<div class="range">
<input type="range" id="range-input" name="range" min="1000" max="20000" value="1000">
<output id="range-output">1000m</output>
</div>
</div>
</div>
</div>
From the documentation the radius needs to be a Number which is the distance in meters; this var distance = radius+'m'; makes it a string.
radius | Type: number
The distance from the given location within which to search for Places, in meters. The maximum allowed value is 50 000.

Changing color for the Multiple Polyline stroke on google map v3 in javascript

I using the same code from http://www.aspsnippets.com/Articles/Google-Maps-V3-Draw-route-line-between-two-geographic-locations-Coordinates-Latitude-and-Longitude-points.aspx here i can have n number of point
I am trying to change the color of stroke it is not reflecting
<!DOCTYPE html >
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var markers = [
{
"title": 'Alibaug',
"lat": '18.641400',
"lng": '72.872200',
"description": 'xxxx'
}
,
{
"title": 'Mumbai',
"lat": '18.964700',
"lng": '72.825800',
"description": 'yyyy'
}
,
{
"title": 'Pune',
"lat": '18.523600',
"lng": '73.847800',
"description": 'zzz'
}
];
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****************//
//Intialize the Path Array
var path = new google.maps.MVCArray();
//Intialize the Direction Service
var service = new google.maps.DirectionsService();
//Set the Path Stroke Color
var poly = new google.maps.Polyline({ map: map, strokeColor: 'red' });
//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) {
for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
path.push(result.routes[0].overview_path[i]);
}
}
});
}
}
}
</script>
<div id="dvMap" style="width: 500px; height: 500px">
</div>
</body>
</html>
and replaced this line with
var poly = new google.maps.Polyline({ map: map, strokeColor: 'red' });
and i tried to add color using the below code as
var colorVariable = ["white","green","blue","yellow","rose"];
for(var a =0;a<=5;a++){
var polyOptions = {
strokeColor: colorVariable[a],
strokeOpacity: 1.0,
strokeWeight: 2
}
poly = new google.maps.Polyline({ map: map, strokeColor: polyOptions });
poly.setMap(map);
}
but i am not getting the different color strokes please say how to integrated it what is wrong in it
A single polyline can only have one color, you need to make a separate polyline for each color:
function getDirections(src, des, color, map) {
//Intialize the Direction Service
var service = new google.maps.DirectionsService();
service.route({
origin: src,
destination: des,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function (result, status) {
if (status == google.maps.DirectionsStatus.OK) {
//Intialize the Path Array
var path = [];
for (var i = 0; i < result.routes[0].overview_path.length; i++) {
path.push(result.routes[0].overview_path[i]);
}
//Set the Path Stroke Color
var polyOptions = {
strokeColor: color,
strokeOpacity: 1.0,
strokeWeight: 2,
path: path,
map: map
}
poly = new google.maps.Polyline(polyOptions);
poly.setMap(map);
}
});
}
proof of concept fiddle
code snippet:
var markers = [{
"title": 'Alibaug',
"lat": '18.641400',
"lng": '72.872200',
"description": 'xxxx'
}, {
"title": 'Mumbai',
"lat": '18.964700',
"lng": '72.825800',
"description": 'yyyy'
}, {
"title": 'Pune',
"lat": '18.523600',
"lng": '73.847800',
"description": 'zzz'
}];
// white is hard to see on the map tiles, removed.
var colorVariable = ["green", "blue", "yellow", "rose"];
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****************//
//Set the Path Stroke Color
var poly = new google.maps.Polyline({
map: map,
strokeColor: 'red'
});
//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];
getDirections(src, des, colorVariable[i], map);
}
}
}
function getDirections(src, des, color, map) {
//Intialize the Direction Service
var service = new google.maps.DirectionsService();
service.route({
origin: src,
destination: des,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
//Intialize the Path Array
var path = [];
for (var i = 0; i < result.routes[0].overview_path.length; i++) {
path.push(result.routes[0].overview_path[i]);
}
//Set the Path Stroke Color
var polyOptions = {
strokeColor: color,
strokeOpacity: 1.0,
strokeWeight: 2,
path: path,
map: map
}
poly = new google.maps.Polyline(polyOptions);
poly.setMap(map);
}
});
}
html,
body,
#dvMap {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="dvMap"></div>
I used a trick to find out which request is being processed, by looking at if (result.request.origin == lat_lng[i]) . (There might exist more elegant solutions)
I added a 4th point (just to see 1 more color, see if it works).
Is this what you want?
<!DOCTYPE html >
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Changing color for the Multiple Polyline stroke on Google maps</title>
</head>
<body>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var polylines = []; // let's make 1 polyline per color
var markers = [
{
"title": 'Alibaug',
"lat": 18.641400,
"lng": 72.872200,
"description": 'xxxx'
},
{
"title": 'Mumbai',
"lat": 18.964700,
"lng": 72.825800,
"description": 'yyyy'
},
{
"title": 'Pune',
"lat": 18.523600,
"lng": 73.847800,
"description": 'zzz'
},
{
"title": 'Kolhapur',
"lat": 16.696530010128207,
"lng": 74.23864138126372,
"description": 'Extra point'
}
];
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****************//
// Make the polyline
//Loop and Draw Path Route between the Points on MAP
for (var i = 0; i< lat_lng.length; i++) {
generatePath(i); // I put this all in a function
}
// we want to know which request is being processed
function indexOfRequest(result) {
for (var i = 0; i <= lat_lng.length; i++) {
if (result.request.origin == lat_lng[i]) {
return i;
}
}
}
function generatePath(i) {
// colors
var colorVariable = ["white", "green", "blue", "yellow", "rose"];
//Intialize the Direction Service
var service = new google.maps.DirectionsService();
//Intialize the Path Array
var path = new google.maps.MVCArray();
var color = colorVariable[i % colorVariable.length]; // the % makes sure the array cycles, so after rose, it's white again
var poly = new google.maps.Polyline({ map: map, strokeColor: color });
polylines.push(poly);
var src = lat_lng[i];
var des = lat_lng[i + 1];
path.push(src);
poly.setPath(path);
// route service
service.route({
origin: src,
destination: des,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function (result, status) {
if (status == google.maps.DirectionsStatus.OK) {
var routeIndex = indexOfRequest(result);
polylines[routeIndex].setPath(result.routes[0].overview_path);
}
});
}
}
</script>
<div id="dvMap" style="width: 500px; height: 500px">
</div>
</body>
</html>
You can change the stroke color only using setOption, this way :
poly.setOptions({strokeColor: 'blue'});
Your polyOption is not an legal value for strokeColor attribute.
You can assing whit your code the strokeColor using the obj.setOptions({attribute: value}) pattern

google map api V3 markers

I am having a problem with google maps, I cant put markers on some location. My idea was to find my location and to put marker on it, then to put markers on other locations but the markers on other locations are not showing on a map.
function success(position) {
var mapcanvas = document.createElement('div');
mapcanvas.id = 'mapcontainer';
mapcanvas.style.height = '550px';
mapcanvas.style.width = '960px';
document.querySelector('article').appendChild(mapcanvas);
var coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var options = {
zoom: 15,
center: coords,
mapTypeControl: false,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("mapcontainer"), options);
var marker = new google.maps.Marker({
position: coords,
map: map,
title: "Vasa lokacija"
});
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success);
} else {
error('Geo Location is not supported');
}
var locations = [
['Banja Luka', 44.766666699999990000, 17.183333299999960000, 4],
['Tuzla', 44.532841000000000000, 18.670499999999947000, 5],
['Zenica', 44.203439200000000000, 17.907743200000027000, 3],
['Sarajevo', 43.850000000000000000, 18.250000000000000000, 2],
['Mostar', 43.333333300000000000, 17.799999999999954000, 1]
];
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][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
The main problem with your function is that your marker adding loop is outside success function, so it never gets called. You also had an extra }at the end of your code. Here is a full solution jsfiddle
var map;
function success(position) {
var mapcanvas = document.createElement('div');
mapcanvas.id = 'mapcontainer';
mapcanvas.style.height = '550px';
mapcanvas.style.width = '960px';
document.querySelector('article').appendChild(mapcanvas);
var coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var options = {
zoom: 15,
center: coords,
mapTypeControl: false,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("mapcontainer"), options);
var marker = new google.maps.Marker({
position: coords,
map: map,
title: "Vasa lokacija"
});
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success);
} else {
error('Geo Location is not supported');
}
var locations = [
['Banja Luka', 44.766666699999990000, 17.183333299999960000, 4],
['Tuzla', 44.532841000000000000, 18.670499999999947000, 5],
['Zenica', 44.203439200000000000, 17.907743200000027000, 3],
['Sarajevo', 43.850000000000000000, 18.250000000000000000, 2],
['Mostar', 43.333333300000000000, 17.799999999999954000, 1]
];
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][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
} //success fn ENDS
var position = {
coords: {
latitude: 44.766666699999990000,
longitude: 17.183333299999960000
}
};
success(position);
the main problem with your code is you are plotting the marker before the map is loaded because it is out side of your function success.try this:I have use static value for center you can change it as per your code.
$(document).ready(function () {
success(position);
});
var position = { // suppose this is your position
coords: {
latitude: 44.666666699999990000,
longitude: 17.183333299999960000
}
};
var map;
var marker, i;
var locations = [
['Banja Luka', 44.766666699999990000, 17.183333299999960000, 4],
['Tuzla', 44.532841000000000000, 18.670499999999947000, 5],
['Zenica', 44.203439200000000000, 17.907743200000027000, 3],
['Sarajevo', 43.850000000000000000, 18.250000000000000000, 2],
['Mostar', 43.333333300000000000, 17.799999999999954000, 1]
];
function success(position) {
var mapcanvas = document.createElement('div');
mapcanvas.id = 'mapcontainer';
mapcanvas.style.height = '550px';
mapcanvas.style.width = '960px';
document.getElementById('article').appendChild(mapcanvas);
var coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var options = {
zoom: 8,
center: coords,
mapTypeControl: false,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("mapcontainer"), options);
marker = new google.maps.Marker({
position: coords,
map: map,
title: "Vasa lokacija"
});
var infowindow = new google.maps.InfoWindow();
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', function (marker, i) {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
});
}
}

Cannot get a different Icon in Google map on change event

I am new to Google API V3. I want to change the Icon on Zoom event. The full code is running as expected, it is the last bit wherein I have given a map change event to capture the change in zoom so that I could change in the icon from a simple circle to Google standard red icon. Please do review and suggest corrections, thank you so much.
<script type="text/javascript" src="util.js"></script>
<script type="text/javascript">
var infowindow;
var map;
function initialize() {
var myLatlng = new google.maps.LatLng(20, 0);
var myOptions = {
zoom: 3,
panControl:true,
zoomControl:true,
mapTypeControl:true,
scaleControl:true,
streetViewControl:true,
overviewMapControl:true,
rotateControl:true,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
downloadUrl("worldcities.xml", function(data) {
var markers = data.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var latlng = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var circleOptions = {
strokeColor: '#FF0000',
strokeOpacity: 0.65,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.25,
map: map,
center: latlng,
radius: parseInt(markers[i].getAttribute("population"))/25
};
var marker = createMarker(markers[i].getAttribute("name"), latlng, markers[i].getAttribute("population"), markers[i].getAttribute("countrycode"), markers[i].getAttribute("region"));
var onekmcircle = new google.maps.Circle(circleOptions);
}
});
}
function createMarker(name, latlng, popl, cntry, rgon) {
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 2
},
title: name});
var contentstring = '<b>'+name+'</b>'+'<br>Population: '+popl+'<br>Country: '+cntry+'<br>Region: '+rgon;
google.maps.event.addListener(marker, "click", function() {
if (infowindow) infowindow.close();
infowindow = new google.maps.InfoWindow({content: contentstring});
infowindow.open(map, marker);
var zoomLevel = map.getZoom();
map.setCenter(marker.getPosition());
if (zoomLevel<6)
{
map.setZoom(6);
}
});
return marker;
}
google.maps.event.addListener(map, 'zoom_changed', function() {
var url ='http://maps.google.com/mapfiles/ms/icons/red-dot.png';
var icon = google.maps.MarkerImage(url);
var currentZoom = map.getZoom();
if (currentZoom >9){
for(i=0; i< markers.length; i++ ) {
markers[i].setIcon(icon);
}
}
});
Here you go...I fixed your code for you...you had a few errors. Biggest one being that you were not saving the markers you created into an array to loop through on the event listener.
I added the gMarkers array. I ran the code in the console of your site and it worked. Let me know if you have any questions.
var infowindow;
var map;
var gMarkers=[];
function initialize() {
var myLatlng = new google.maps.LatLng(20, 0);
var myOptions = {
zoom: 3,
panControl:true,
zoomControl:true,
mapTypeControl:true,
scaleControl:true,
streetViewControl:true,
overviewMapControl:true,
rotateControl:true,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
downloadUrl("worldcities.xml", function(data) {
markers = data.documentElement.getElementsByTagName("marker");
});
for (var i = 0; i < markers.length; i++) {
var latlng = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")),parseFloat(markers[i].getAttribute("lng")));
var circleOptions = {
strokeColor: '#FF0000',
strokeOpacity: 0.65,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.25,
map: map,
center: latlng,
radius: parseInt(markers[i].getAttribute("population"))/25
};
gMarkers.push(createMarker(markers[i].getAttribute("name"), latlng,markers[i].getAttribute("population"), markers[i].getAttribute("countrycode"), markers[i].getAttribute("region")));
var onekmcircle = new google.maps.Circle(circleOptions);
}
google.maps.event.addListener(map, 'zoom_changed', function() {
var url ='http://maps.google.com/mapfiles/ms/icons/red-dot.png';
var icon = google.maps.MarkerImage(url);
var currentZoom = map.getZoom();
if (currentZoom >9){
for(var i=0; i< gMarkers.length; i++ ) {
gMarkers[i].setIcon(icon);
}
}else{
for(var i=0; i< gMarkers.length; i++ ) {
gMarkers[i].setIcon({path: google.maps.SymbolPath.CIRCLE,scale: 2});
}
}
});
}
function createMarker(name, latlng, popl, cntry, rgon) {
marker = new google.maps.Marker({
position: latlng,
map: map,
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 2
},
title: name
});
var contentstring = '<b>'+name+'</b>'+'<br>Population: '+popl+'<br>Country: '+cntry+'<br>Region: '+rgon;
google.maps.event.addListener(marker, "click", function() {
if (infowindow) infowindow.close();
infowindow = new google.maps.InfoWindow({content: contentstring});
infowindow.open(map, marker);
var zoomLevel = map.getZoom();
map.setCenter(marker.getPosition());
if (zoomLevel<6){
map.setZoom(6);
}
});
return marker;
}
google.maps.event.addListener(marker,\'mouseover\', function() {
marker.setIcon("fileadmin/new_templates/images/home_map_notification_hover.png");
$.ajax({
type: "POST",
async : false,
data: \'address=\'+add ,
success: function(html){
infowindow.setContent(html);
infowindow.open(map,marker);
},
});
});
// On Mouse out
google.maps.event.addListener(infowindow, \'mouseout\', function () {
marker.setIcon("fileadmin/new_templates/images/home_page_map_notification.png");
});
// On Infowindow close
google.maps.event.addListener(infowindow, \'closeclick\', function () {
marker.setIcon("fileadmin/new_templates/images/home_page_map_notification.png");
});

Categories

Resources