I am a student trying to become a java developer in Korea
I want to draw a polyline connecting the markers with a click event, not with directions.
I'll give you an exampleenter image description here
It's not finished yet, but I'll show you what I made
I made a mistake but please understand
What I want is to draw a polyline by connecting two fixed markers.
var map, polyline,markers = new Array();
var stockholm = {lat:45,lng:10}; // 맵 중앙 설정
function initMap(){
// map options
var options = {
zoom:4,
center:stockholm,
streetViewControl: true,
draggable:true,
mapTypeId: "roadmap",
// 맵 기본 컨트롤 설정
mapTypeControl: true,
mapTypeControlOptions: {
position: google.maps.ControlPosition.RIGHT_TOP
},
panControl: true,
panControlOptions: {
position: google.maps.ControlPosition.RIGHT_TOP
},
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL,
position: google.maps.ControlPosition.RIGHT_TOP
},
scaleControl: true
}
// Map 호출 ======================================================================
map = new google.maps.Map(document.getElementById('map'),options);
// polyline 옵션 지정 ============================================================
polyline = new google.maps.Polyline({
strokeColor: 'red',
strokeWeight: 3,
map: map
});
google.maps.event.addListener(map, 'click', function (event) {
addPoint(event.latLng);
});
// searchbox===================
const input = document.getElementById("pac-input");
const searchBox = new google.maps.places.SearchBox(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
let markers1 = [];
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener("places_changed", () => {
const places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers1.forEach((marker) => {
marker.setMap(null);
});
markers1 = [];
// For each place, get the icon, name and location.
const bounds = new google.maps.LatLngBounds();
places.forEach((place) => {
if (!place.geometry || !place.geometry.location) {
console.log("Returned place contains no geometry");
return;
}
const icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25),
};
// Create a marker for each place.
markers1.push(new google.maps.Marker({
map,
icon,
title: place.name,
position: place.geometry.location,
}));
if (place.geometry.viewport) {
bounds.union(place.geometry.viewport);
}else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
// 고정 마커 추가
var markers = [
// 가나
{
coords:{lat:6.6666004, lng:-1.6162709},
iconImage:'assets/img/places/stparkdublin.png',
content:'<div style="height:auto;width:400px;"><h1>가나-쿠마시</h1>쿠마시는 가나 아샨티 주의 주도이며 구 아샨티 왕국의 수도였다. 수도인 아크라에서 북서쪽으로 약 250km 떨어져 있다. 쿠마시는 적도로부터 북쪽으로 약 482km, 기니만으로터 북쪽으로 약 160km 에 위치한다.',
},
{
coords:{lat:5.6037168,lng:-0.1869644},
iconImage:'assets/img/places/botanic garden.png',
content:'<div style="height:auto;width:400px;"><h1>가나-아크라</h1>아크라는 가나 공화국의 수도이자 약 227만 명의 인구를 가진 가나 최대의 도시이다. 도시 자체도 아크라 메트로폴리스 특구에 속해 있으며, 그 면적은 약 139km²이다. 아크라의 관광지 중에 가나 국립 박물관이 있다. 코토카 국제공항이 있다.',
},
{
coords:{lat:5.1315, lng:-1.2794744},
iconImage:'assets/img/places/stparkdublin.png',
content:'<div style="height:auto;width:400px;"><h1>가나-케이프코스트</h1>케이프코스트는 가나의 항구 도시로, 중앙 주의 주도이다. 16세기부터 영국과 포르투갈, 스웨덴, 덴마크, 네덜란드의 통치를 받았다. 15세기 포르투갈이 이 곳을 발견했으며 1653년 스웨덴이 케이프코스트 성을 건설했다. 이 성은 현재 세계유산으로 지정되어 있다.',
},
{
coords:{lat:9.393908, lng:-0.8556313999999999},
iconImage:'assets/img/places/swordscastle.png',
content:'<div style="height:auto;width:400px;"><h1>가나-타말레</h1>타말레은 가나 북부 주의 주도이다. 인구는 55만명이다.',
},
{
coords:{lat:10.7875419, lng:-0.8579818},
iconImage:'assets/img/places/Howth.png',
content:'<div style="height:auto;width:400px;"><h1>가나-볼가탕가</h1>볼가탕가는 가나의 도시이다. 경작과 가축 사육이 주된 생업이다.',
},
];
var gmarkers = [];
for(var i = 0; i < markers.length; i++){
gmarkers.push(addMarker(markers[i]));
}
const sidebar = document.getElementById("sidebar"); // sidebar
var activeInfoWindow = null;
//Add MArker function
function addMarker(props){
var marker = new google.maps.Marker({
position:props.coords,
map:map,
descrip:props.content,
});
//Check content
if(props.content){
var infoWindow = new google.maps.InfoWindow({
content:props.content
});
marker.addListener('click',function(){
infoWindow.open(map,marker);
for(var i=0;i<markers.length;i++){
sidebar.innerHTML = props.content;
}
});
marker.addListener('click', function () {
if (activeInfoWindow) { activeInfoWindow.close();}
infoWindow.open(map, marker);
activeInfoWindow = infoWindow;
});
}
return marker;
}
var markerCluster = new MarkerClusterer(map, gmarkers,
{
imagePath:'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m',
gridSize:100,
minClusterSize:10,
});
}
google.maps.event.addDomListener(window, 'load', initMap);
//poly line ======================================================================
var latlnglatlng = new Array;
function removePoint(marker) {
for (var i = 0; i < markers.length; i++) {
if (markers[i] === marker) {
markers[i].setMap(null);
markers.splice(i, 1);
polyline.getPath().removeAt(i);
}
}
}
function addPoint(latlng) {
var marker = new google.maps.Marker({
position: latlng,
map: map
});
markers.push(marker);
//console.log(markers.position.lng.Scopes);
polyline.getPath().setAt(markers.length - 1, latlng);
google.maps.event.addListener(marker, 'click', function (event) {
removePoint(marker);
});
}
#map {
height: 100%;
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDjtW34Ax16khc7UYth6--V4pNFX1XlHUE&libraries=places"></script>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js"></script>
Thanks again for watching I really want to solve this, I've been thinking about it for a month
Related
Hi i have a Google Map that automatically check for user location and put the location to center. I am having problem with putting the marker at the center. I am currently adding marker when you click somewhere.
I also want to clear existing markers when another position is clicked.
var markers = [];
window.onload = function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
}
var mapOptions = {
center: new google.maps.LatLng(21.3891, 39.8579),
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
};
var infoWindow = new google.maps.InfoWindow();
var latlngbounds = new google.maps.LatLngBounds();
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
// This event listener calls addMarker() when the map is
// clicked.
map.addListener('click', function(e) {
placeMarker(e.latLng, map);
});
function placeMarker(position, map) {
var marker = new google.maps.Marker({
position: position,
map: map
});
map.panTo(position);
}
google.maps.event.addListener(map, 'click', function(e) {
document.getElementById("lat").value = (e.latLng.lat());
document.getElementById("lng").value = (e.latLng.lng());
div = document.getElementById('name');
div.style.display = "block";
div = document.getElementById('submit');
div.style.display = "block";
var element = document.getElementById('spacing');
element.style.margin = null;
});
}
#map {
height: 100%;
margin: 0px;
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA-2vW1cIR0t0ZVfVdCmcxx0QEV4C3l6hk&callback=myMap"></script>
<div id="map" style="width:100%; height:505px ; z-index: 1;">
</div>
Hi added this code to the existing code to add marker to center:
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
map.setCenter(pos);
var marker = new google.maps.Marker({ position: pos, animation:
google.maps.Animation.BOUNCE, icon: 'img/mapicon.png' });
marker.setMap(map);
},
function() {
handleLocationError(true, infoWindow, map.getCenter());
});
}
For the secoind solution, i added this :
function placeMarker(position, map) {
var marker = new google.maps.Marker({
position: position,
icon: 'img/mapicon.png',
map: map
});
map.panTo(position);
markers.push(marker);
}
function setMapOnAll(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
function clearMarker(position, map) {
setMapOnAll(null);
}
i follow tutorial on this link : https://developers.google.com/maps/documentation/javascript/examples/directions-complex to create maps direction. when i costumized it in my map, it doesnt work. i think it because addEventListener not work because my wrong code. anyone can help me?
demo on plunker : https://plnkr.co/edit/FzYTtgv2WriPVRJJMt6S?p=preview
here is my direction code :
//direction config starts here
var directionsService = new google.maps.DirectionsService;
// Create a renderer for directions and bind it to the map.
var directionsDisplay = new google.maps.DirectionsRenderer({map: map});
// Instantiate an info window to hold step text.
var stepDisplay = new google.maps.InfoWindow;
// Display the route between the initial start and end selections.
calculateAndDisplayRoute(
directionsDisplay, directionsService, markerArray, stepDisplay, map);
// Listen to change events from the start and end lists.
var onChangeHandler = function() {
calculateAndDisplayRoute(
directionsDisplay, directionsService, markerArray, stepDisplay, map);
};
document.getElementById('start').addEventListener('change', onChangeHandler);
document.getElementById('end').addEventListener('change', onChangeHandler);
function calculateAndDisplayRoute(directionsDisplay, directionsService,
markerArray, stepDisplay, map) {
// First, remove any existing markers from the map.
for (var i = 0; i < markerArray.length; i++) {
markerArray[i].setMap(null);
}}
// Retrieve the start and end locations and create a DirectionsRequest using
// WALKING directions.
directionsService.route({
origin: document.getElementById('start').value,
destination: document.getElementById('end').value,
travelMode: google.maps.TravelMode.WALKING
}, function(response, status) {
// Route the directions and pass the response to a function to create
// markers for each step.
if (status === google.maps.DirectionsStatus.OK) {
document.getElementById('warnings-panel').innerHTML =
'<b>' + response.routes[0].warnings + '</b>';
directionsDisplay.setDirections(response);
showSteps(response, markerArray, stepDisplay, map);
} else {
window.alert('Directions request failed due to ' + status);
}
});
function showSteps(directionResult, markerArray, stepDisplay, map) {
// For each step, place a marker, and add the text to the marker's infowindow.
// Also attach the marker to an array so we can keep track of it and remove it
// when calculating new routes.
var myRoute = directionResult.routes[0].legs[0];
for (var i = 0; i < myRoute.steps.length; i++) {
var markerss = markerArray[i] = markerArray[i] || new google.maps.Marker;
markerss.setMap(map);
markerss.setPosition(myRoute.steps[i].start_location);
attachInstructionText(
stepDisplay, markerss, myRoute.steps[i].instructions, map);
}
}
function attachInstructionText(stepDisplay, markerss, text, map) {
google.maps.event.addListener(markerss, 'click', function() {
// Open an info window when the marker is clicked on, containing the text
// of the step.
stepDisplay.setContent(text);
stepDisplay.open(map, markerss);
});
}
//ends of directions
Thankyou in advance -
calculateAndDisplayRoute() currently only removes the markers, but doesn't draw the routes.
Fixed script:
var map;
var markerArray = [];
var markers = [];
var feature = [];
var i, marker,markerss;
var content = '<html> <style type="text/css">.enjoy-css {-webkit-box-sizing: content-box-moz-box-sizing: content-box;box-sizing: content-box; padding: 19px; border: none; -webkit-border-radius: 3px; border-radius: 3px;font: normal 16px/1 "Comic Sans MS", cursive, sans-serif;color: black;-o-text-overflow: ellipsis;text-overflow: ellipsis;background: -webkit-linear-gradient(0deg, rgba(252,234,187,1) 0, rgba(252,205,77,1) 18%, rgba(248,181,0,1) 82%, rgba(251,223,147,1) 100%);background: -moz-linear-gradient(90deg, rgba(252,234,187,1) 0, rgba(252,205,77,1) 18%, rgba(248,181,0,1) 82%, rgba(251,223,147,1) 100%);background: linear-gradient(90deg, rgba(252,234,187,1) 0, rgba(252,205,77,1) 18%, rgba(248,181,0,1) 82%, rgba(251,223,147,1) 100%);background-position: 50% 50%;-webkit-background-origin: padding-box;background-origin: padding-box;-webkit-background-clip: border-box;background-clip: border-box;-webkit-background-size: auto auto;background-size: auto auto;-webkit-box-shadow: 0 0 0 3px rgba(100,103,119,1) inset; box-shadow: 0 0 0 3px rgba(100,103,119,1) inset; -webkit-transform: rotateY(-20.626480624709636deg) ; transform: rotateY(-20.626480624709636deg) ;}</style> <body><br><div class="enjoy-css">';
function initialize() {
//initialize peta
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 16,
center: new google.maps.LatLng(-8.704956, 115.22750),
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
position: google.maps.ControlPosition.TOP_CENTER
}
});
//setting traffic layer option.
var trafficLayer = new google.maps.TrafficLayer();
trafficLayer.setMap(map);
//define infowindow
var infowindow = new google.maps.InfoWindow({
content: ''
});
//direction config starts here
var directionsService = new google.maps.DirectionsService;
// Create a renderer for directions and bind it to the map.
var directionsDisplay = new google.maps.DirectionsRenderer({map: map});
// Instantiate an info window to hold step text.
var stepDisplay = new google.maps.InfoWindow;
// Display the route between the initial start and end selections.
calculateAndDisplayRoute(
directionsDisplay, directionsService, markerArray, stepDisplay, map);
// Listen to change events from the start and end lists.
var onChangeHandler = function() {
calculateAndDisplayRoute(
directionsDisplay, directionsService, markerArray, stepDisplay, map);
};
document.getElementById('start').addEventListener('change', onChangeHandler);
document.getElementById('end').addEventListener('change', onChangeHandler);
function calculateAndDisplayRoute(directionsDisplay, directionsService,
markerArray, stepDisplay, map) {
// First, remove any existing markers from the map.
for (var i = 0; i < markerArray.length; i++) {
markerArray[i].setMap(null);
}
// Retrieve the start and end locations and create a DirectionsRequest using
// WALKING directions.
directionsService.route({
origin: document.getElementById('start').value,
destination: document.getElementById('end').value,
travelMode: google.maps.TravelMode.WALKING
}, function(response, status) {
// Route the directions and pass the response to a function to create
// markers for each step.
if (status === google.maps.DirectionsStatus.OK) {
document.getElementById('warnings-panel').innerHTML =
'<b>' + response.routes[0].warnings + '</b>';
directionsDisplay.setDirections(response);
showSteps(response, markerArray, stepDisplay, map);
} else {
window.alert('Directions request failed due to ' + status);
}
});
function showSteps(directionResult, markerArray, stepDisplay, map) {
// For each step, place a marker, and add the text to the marker's infowindow.
// Also attach the marker to an array so we can keep track of it and remove it
// when calculating new routes.
var myRoute = directionResult.routes[0].legs[0];
for (var i = 0; i < myRoute.steps.length; i++) {
var markerss = markerArray[i] = markerArray[i] || new google.maps.Marker;
markerss.setMap(map);
markerss.setPosition(myRoute.steps[i].start_location);
attachInstructionText(
stepDisplay, markerss, myRoute.steps[i].instructions, map);
}
}
function attachInstructionText(stepDisplay, markerss, text, map) {
google.maps.event.addListener(markerss, 'click', function() {
// Open an info window when the marker is clicked on, containing the text
// of the step.
stepDisplay.setContent(text);
stepDisplay.open(map, markerss);
});
}}
//ends of directions
//define searchbox function start here
var input = document.getElementById('locationTextField');
var searchBox = new google.maps.places.SearchBox(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// Bias the SearchBox results towards current map's viewport.
map.addListener('bounds_changed', function() {
searchBox.setBounds(map.getBounds());
});
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function(place) {
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
var autocomplete = new google.maps.places.Autocomplete(input);
//search box function end here
//define marker icon
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
var icons = {
parking: {
name: 'Parking',
icon: iconBase + 'parking_lot_maps.png'
},
library: {
name: 'Library',
icon: iconBase + 'library_maps.png'
},
info: {
name: 'Info',
icon: iconBase + 'info-i_maps.png'
}
};
/*
function addMarker(feature, map) {
marker = new google.maps.Marker({
position: feature.position,
icon: icons[feature.type].icon,
map: map
});
// marker.category = feature[i]['category'];
marker.setVisible(true);
markers.push(marker);
}*/
// define marker position
var features = [{
position: new google.maps.LatLng(-8.702709, 115.224461),
type: 'info',
title: 'Pusat Informasi Kota',
category: 1
}, {
position: new google.maps.LatLng(-8.704432, 115.230249),
type: 'parking',
title: 'Tempat Parkir Avaliable',
category: 2
}, {
position: new google.maps.LatLng(-8.704442, 115.231239),
type: 'library',
title: 'perpustakaan kota',
category: 3
}, {
position: new google.maps.LatLng(-8.702909, 115.230149),
type: 'parking',
title: 'ini parkir',
category: 2
}, {
position: new google.maps.LatLng(-8.602709, 115.230241),
type: 'library',
title: 'ini perpus',
category: 3
}, {
position: new google.maps.LatLng(-8.402709, 115.230211),
type: 'info',
title: 'ini info',
category: 1
}, {
position: new google.maps.LatLng(-8.402704, 115.230114),
type: 'parking',
title: 'ini parkir',
category: 2
}, {
position: new google.maps.LatLng(-8.401704, 115.130114),
type: 'library',
title: 'ini library',
category: 3
}, {
position: new google.maps.LatLng(-8.401708, 115.130117),
type: 'info',
title: 'ini info',
category: 1
}, {
position: new google.maps.LatLng(-8.401608, 115.130107),
type: 'library',
title: 'ini library 1',
category: 3
}];
//Adding marker into map
for (var i = 0, feature; feature = features[i]; i++) {
marker = new google.maps.Marker({
position: feature.position,
animation: google.maps.Animation.DROP,
icon: icons[feature.type].icon,
map: map
});
marker.category = features[i]['category'];
marker.setVisible(false);
markers.push(marker);
google.maps.event.addListener(marker, 'click', (function(marker, feature) {
return function() {
infowindow.setContent(content + " " + feature['title'] + "</div><br></body</html>");
infowindow.setOptions({
maxWidth: 200
});
infowindow.open(map, marker);
}
})(marker, feature));
}
//define and show floating information on right map
var legend = document.getElementById('legend');
for (var key in icons) {
var type = icons[key];
var name = type.name;
var icon = type.icon;
var div = document.createElement('div');
div.innerHTML = '<img src="' + icon + '"> ' + name;
legend.appendChild(div);
}
map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(legend);
//function for hide and show POI info
window.showPOI1 = function(t) {
if (t.is(':checked')) {
//alert('checked');
for (i = 0; i < markers.length; i++) {
if (markers[i].category === 1) {
markers[i].setVisible(true);
markers[i].setAnimation(google.maps.Animation.BOUNCE);
}
}
} else {
infowindow.close();
for (i = 0; i < markers.length; i++) {
if (markers[i].category === 1) {
markers[i].setVisible(false);
}
}
}
}
//function for hide and show POI parking
window.showPOI2 = function(t) {
if (t.is(':checked')) {
//alert('checked');
for (i = 0; i < markers.length; i++) {
if (markers[i].category === 2) {
markers[i].setVisible(true);
markers[i].setAnimation(google.maps.Animation.DROP);
}
}
} else {
infowindow.close();
for (i = 0; i < markers.length; i++) {
if (markers[i].category === 2) {
markers[i].setVisible(false);
}
}
}
}
//function for hide and show POI Library
window.showPOI3 = function(t) {
if (t.is(':checked')) {
for (i = 0; i < markers.length; i++) {
if (markers[i].category === 3) {
markers[i].setVisible(true);
markers[i].setAnimation(google.maps.Animation.DROP);
}
}
} else {
infowindow.close();
for (i = 0; i < markers.length; i++) {
if (markers[i].category === 3) {
markers[i].setVisible(false);
}
}
}
}
onChangeHandler();
}
https://plnkr.co/edit/JfCH1T8khOCewoNSJYBE?p=preview
I am new to Meteor and Javascript. I am creating a map that gives directions from your current location to a marker on the map. Everything seems to work except that I can't seem to call the calcRoute() function correctly. Or maybe it is defined in the wrong place.
I think I need some schooling on template helpers. Please tell me where I went wrong. Thanks.
var gmaps = {
// map object
map: null,
//direction services object
directionsService: null,
//direction services object
directionsDisplay: null,
//direction services object
stepDisplay: null,
markerArray: []
}
Template.map.helpers({
mapOptions: function() {
if (GoogleMaps.loaded()) {
if (!Geolocation.error()) {
pos = Geolocation.latLng();
}
return {
//center: new google.maps.LatLng(-25.2743, 133.7751),
center: new google.maps.LatLng(pos.lat, pos.lng),
zoom: 12,
scaleControl: false,
zoomControl: false,
mapTypeControl: false,
panControl: false,
rotateControl: true,
overviewMapControl: false,
streetViewControl: false,
};
}
},
calcRoute: function() {
//clear markers before calculating function
gmaps.clearMarkers();
console.log(this.markerArray);
// Retrieve the start and end locations and create
// a DirectionsRequest using BICYCLING directions.
var start = marker3.getPosition();
var end = document.getElementById('marketName').value;
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.BICYCLING
};
// Route the directions and pass the response to a
// function to create markers for each step.
this.directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var warnings = document.getElementById('warnings_panel');
warnings.innerHTML = '<b>' + response.routes[0].warnings + '</b>';
this.directionsDisplay.setDirections(response);
gmaps.showSteps(response);
}
});
},
showSteps: function(directionResult) {
// For each step, place a marker, and add the text to the marker's
// info window. Also attach the marker to an array so we
// can keep track of it and remove it when calculating new
// routes.
var myRoute = directionResult.routes[0].legs[0];
for (var i = 0; i < myRoute.steps.length; i++) {
var marker = new google.maps.Marker({
position: myRoute.steps[i].start_location,
map: map.instance
});
gmaps.attachInstructionText(marker, myRoute.steps[i].instructions);
this.markerArray[i] = marker;
}
},
attachInstructionText: function(marker, text) {
// Instantiate an info window to hold step text.
var stepDisplay = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'mouseover', function() {
// Open an info window when the marker is clicked on,
// containing the text of the step.
stepDisplay.setContent(text);
stepDisplay.open(map.instance, marker);
})
google.maps.event.addListener(marker, 'click', function() {
map.instance.setZoom(14);
map.instance.setCenter(marker.getPosition());
stepDisplay.open(map.instance, marker);
})
},
clearMarkers: function() {
// First, remove any existing markers from the map.
for (var i = 0; i < this.markerArray.length; i++) {
this.markerArray[i].setMap(null);
}
// Now, clear the array itself.
this.markerArray = [];
}
});
Template.map.onCreated(function() {
GoogleMaps.ready('map', function(map) {
var bikeLayer = new google.maps.BicyclingLayer();
bikeLayer.setMap(map.instance);
var marker1 = new google.maps.Marker({
position: new google.maps.LatLng(29.71739, -95.40183),
map: map.instance,
title: 'Rice U Farmers Market'
});
var infowindow1 = new google.maps.InfoWindow({
content: ''
});
google.maps.event.addListener(marker1, 'click', function() {
infowindow1.setContent( '<p>Farmers Market at Rice U </p>' +'<button onclick="Meteor.call(calcRoute());">Directions from my Location</button>');
infowindow1.open(map.instance, marker1);
});
var marker2 = new google.maps.Marker({
position: new google.maps.LatLng(29.81063, -95.37999),
map: map.instance,
title: 'Canino\'s Produce'
});
var infowindow2 = new google.maps.InfoWindow({
content: 'Canino\'s Produce'
});
google.maps.event.addListener(marker2, 'click', function() {
infowindow2.open(map.instance, marker2);
});
var image = '/img/app/flag1.png'
var marker3 = new google.maps.Marker({
position: new google.maps.LatLng(pos.lat, pos.lng),
map: map.instance,
title: 'You are here',
icon: image
});
var rendererOptions = {
map: map.instance
}
this.directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
// global flag saying we intialized already
Session.set('map', true);
})
});
You have to pass the name of the method that Meteor will call as a string;
Replace:
'<p>Farmers Market at Rice U </p>' +'<button onclick="Meteor.call(calcRoute());">Directions from my Location</button>');
infowindow1.open(map.instance, marker1);
with:
'<p>Farmers Market at Rice U </p>' +'<button onclick="Meteor.call(\'calcRoute\');">Directions from my Location</button>');
infowindow1.open(map.instance, marker1);
I am trying to have places come up on the map based on the users geolocation. I know the geolocation works and map shows up, but none of the markers come up showing the local businesses. I am not getting any errors in console as well. I made sure that the script in my html is passing both the library and the API key, but just in case, here is the script:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places&key=MY_KEY"></script>
Here is my JavaScript...
var map;
var infowindow;
var service;
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 13,
mapTypeControl: false,
panControl: true,
panControlOptions: {
position: google.maps.ControlPosition.TOP_RIGHT
},
zoomControl: true,
zoomControlOptions: {
position: google.maps.ControlPosition.RIGHT_CENTER
},
scaleControl: true,
streetViewControl: false
});
// Start Geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Found You!'
});
var request = {
location: pos,
radius: 500,
types: ['store']
};
infowindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
// Callback for Places
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
createMarker(results[i]);
}
}
}
// Create Marker for Places
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);
});
}
// Google Maps Error Flags
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
Here is my updated coded that I got to work.. I made some customizations to the markers, but this works now. As mentioned in the comments, I believe the issue had to do with the variables set for infowindow. I changed the geolocation one to 'infowindowLocation' instead and adjusted in the error flags section.
var map;
var infowindow;
var service;
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 13,
mapTypeControl: false,
panControl: true,
panControlOptions: {
position: google.maps.ControlPosition.TOP_RIGHT
},
zoomControl: true,
zoomControlOptions: {
position: google.maps.ControlPosition.RIGHT_CENTER
},
scaleControl: true,
streetViewControl: false
});
// Start Geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindowLocation = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Found You!'
});
var request = {
location: pos,
radius: 3218.69,
types: ['dentist']
};
infowindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
// Callback for Places
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
createMarker(results[i]);
}
}
}
// Create Marker for Places
function createMarker(place) {
var placeLoc = place.geometry.location;
var image = 'img/flag.png';
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
title: place.name,
animation: google.maps.Animation.DROP,
icon: image
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map,marker);
});
}
// Google Maps Error Flags
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindowLocation = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
initialize();
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);
});
}
}