Sometimes, when I click on a marker once, all of the markers disappear for a second and reappear. Then I have to click again on a marker for the click event to register and the Info-Box to display. I am pretty sure this is also the reason why my markers don't disappear when I call the clearMarkers() function if I haven't already clicked on a marker. Here is my code:
var map;
var markersArray = [];
var cat = "restaurants, All";
var C = [...];
var D = [...];
function initMap() {
// Create a map object and specify the Div element to display it on
loc = {lat: 41.902783, lng: 12.496366};
map = new google.maps.Map(document.getElementById('map'), {
center: loc,
zoom: 14,
disableDefaultUI: true
});
// Displays all of the markers when page loads, all restaurants
getJsonData('yelpdata.php?cat=restaurants, All&lat='+loc.lat+'&lng='+loc.lng, map);
var filtersPanel = document.getElementById('filtersPanel');
var textField1 = document.getElementById('userInput');
// Displays the markers according the value the user is typing (cat)
function useValue() {
clearMarkers();
var textFieldVal = textField1.value;
var ind = findIndex(textFieldVal);
if (ind != -1) {
cat = D[ind];
}
getJsonData('yelpdata.php?cat='+cat+'&lat='+loc.lat+'&lng='+loc.lng, map);
}
// Text box event handlers
//textField1.oninput = useValue;
textField1.onchange = useValue;
textField1.addEventListener("awesomplete-selectcomplete", useValue);
google.maps.event.addListener(map, 'click', function(event) {
latitude = event.latLng.lat();
longitude = event.latLng.lng();
newCenter = {lat: latitude, lng: longitude};
map.setCenter(newCenter);
loc = newCenter;
useValue();
});
var autocomplete = new Awesomplete(textField1, {
list: C,
filter: Awesomplete.FILTER_STARTSWITH,
minChars: 1,
autoFirst: true
});
// Displays the filters panel in the top-left of the screen
map.controls[google.maps.ControlPosition.TOP_LEFT].push(filtersPanel);
}
function findIndex(cat) {
for(var i=0; i<C.length; i++) {
if(C[i] == cat)
return i;
}
return -1;
}
function clearMarkers() {
// Clears the markers from the map and array
for (var i=0; i < markersArray.length; i++) {
markersArray[i].setMap(null);
}
markersArray = [];
}
function getJsonData(url, map) {
// Using AJAX to get the JSON data from the 'yelpdata.php' file and display markers with info-boxes on the map
var request = new XMLHttpRequest; // the main object to request the XML
request.onreadystatechange = function() { // when the request changes state
if (request.readyState == 4) { // success, we have recieved the XML object from sending the request
var json = request.responseText;
var obj = JSON.parse(json);
var numMarkers = obj.businesses.length;
document.getElementById("numResults").innerHTML = numMarkers + " results";
for (var i = 0; i < obj.businesses.length; i++) {
(function(index) {
// Getting all of the attributes for each business from the JSON
var business = obj.businesses[index];
var name = business.name;
var catArr = business.categories;
var catStr = "";
for (j=0; j < catArr.length; j++) {
if (j == 0) {
catStr += catArr[j].title;
} else if (j > 0) {
catStr += ", " + catArr[j].title;
}
}
var reviews = business.review_count;
var rating = business.rating;
var address = business.location.address1 + ", " + business.location.city + ", " + business.location.state;
var coord = {lat: business.coordinates.latitude,
lng: business.coordinates.longitude};
var url = business.url;
var img_url = business.image_url;
// Creating the info-box
var markerInfo = document.createElement('div');
var title = document.createElement('strong'); // name
title.textContent = name;
var text0 = document.createElement('text'); // categories
text0.textContent = catStr;
var text1 = document.createElement('text'); // address
text1.textContent = address;
var text2 = document.createElement('text'); // reviews
text2.textContent = reviews + " reviews";
var text3 = document.createElement('text'); // rating
text3.textContent = rating + " stars";
// Appending the text to the info-box
markerInfo.appendChild(title);
markerInfo.appendChild(document.createElement('br'));
markerInfo.appendChild(text0);
markerInfo.appendChild(document.createElement('br'));
markerInfo.appendChild(text1);
markerInfo.appendChild(document.createElement('br'));
markerInfo.appendChild(text2);
markerInfo.appendChild(document.createElement('br'));
markerInfo.appendChild(text3);
// create the marker on its according position and append into array
var marker = new google.maps.Marker({
map: map,
position: coord
});
// change the opacity of the markers according to rating
if (rating >= 4) {
marker.setOpacity(1.0);
} else if (rating >= 2.5 && rating < 4) {
marker.setOpacity(0.8);
} else if (rating < 2.5) {
marker.setOpacity(0.6);
}
// set the info-box to the marker on click
infoWindow = new google.maps.InfoWindow;
marker.addListener('click', function() {
console.log("Registering");
infoWindow.setContent(markerInfo);
infoWindow.open(map, marker);
});
markersArray.push(marker);
})(i);
}
}
};
request.open('GET', url); // initialize the request
request.send(); // send the request
}
Lets see if this helps...
In this batch of code you are building the infobox content but not setting it until the click event.
// set the info-box to the marker on click
infoWindow = new google.maps.InfoWindow;
marker.addListener('click', function() {
console.log("Registering");
infoWindow.setContent(markerInfo);
infoWindow.open(map, marker);
});
try moving the line that sets the content outside the click event. you should only need to set it once anyway
infoWindow = new google.maps.InfoWindow;
infoWindow.setContent(markerInfo);
marker.addListener('click', function() {
console.log("Registering");
infoWindow.open(map, marker);
});
I have a list of events that I display as markers on a map(its web application/site) and I would like to show only events in a certain distance (10 KM) from the user current location So, how can I combine this 2
//User Location
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(
function (position) {
var currentLatitude = position.coords.latitude;
var currentLongitude = position.coords.longitude;
// alert ("Latitude"+currentLatitude+"Longitude"+currentLongitude);window.mapServiceProvider(position.coords.latitude,position.coords.longitude);
// console.log(position);
}
);
}
//List of location from the Db.
var markers = #Html.Raw(Json.Encode(Model.UpcomingLectureGigs));
//Set All merkers on the map
window.onload = function (a) {
var mapOptions = {
center: new window.google.maps.LatLng(window.markers[0].Latitude, window.markers[0].Longitude),
zoom: 12,
mapTypeId: window.google.maps.MapTypeId.ROADMAP
};
var infoWindow = new window.google.maps.InfoWindow();
var map = new window.google.maps.Map(document.getElementById("dvMap"), mapOptions);
for (var i = 0; i < window.markers.length; i++) {
var data = window.markers[i];
var myLatlng = new window.google.maps.LatLng(data.Latitude, data.Longitude);
// console.log(data.Latitude, data.Longitude);
var marker = new window.google.maps.Marker({
position: myLatlng,
draggable: true,
animation: google.maps.Animation.DROP,
get map() { return map; }
});
(function (marker, data) {
window.google.maps.event.addListener(marker,
"click",
function (e) {
infoWindow.setContent(data
.Venue +
" " +
data.Genre.Name +
" " +
data.DateTime.toString("dd/mm/yy"));
//.toISOString().split("T")[0]);
// .format('MM/DD h:mm');
infoWindow.open(map, marker);
});
})(marker, data);
};
};
You can use a geometry library to calculate distance in meters between the user location and marker.
https://developers.google.com/maps/documentation/javascript/reference#spherical
The code snapshot to filter markers may be something like
var markers_filtered = markers.filter(function(marker, index, array) {
var myLatlng = new window.google.maps.LatLng(marker.Latitude, marker.Longitude);
return google.maps.geometry.spherical.computeDistanceBetween(userLatLng, myLatlng) < 10000;
});
for (var i = 0; i < markers_filtered.length; i++) {
//Your stuff here
}
You should add libraries=geometry parameter when you load Maps JavaScript API.
https://developers.google.com/maps/documentation/javascript/geometry
I am working on a google maps project where I am populating the google maps with markers being read from a database (drawMarkers function). Along with that the google maps finds your current location and keeps refreshing it every couple of seconds to keep track of you on the map. My issue is that have a var closest which is also a function i am using the too find the closest marker then create directions to current locations from there. I did not know how to actually find the closest marker so i borrowed the code from another question from stack overflow and tried to adapt it to this project. I need help to get my closest function to find the closest marker and then to make it the destination in the direction service
$ionicSideMenuDelegate.canDragContent(false);
$scope.getTourMarkers = function () {
tourmarkers.getTourMarkers().success(function (data) {
$scope.tourmarkers = data;
console.log($scope.tourmarkers);
drawMarkers();
});
};
var drawMarkers = function () {
var markers;
var content;
var infoWindow;
for (var i = 0; i < $scope.tourmarkers.length; i++) {
content = '<h2>' + $scope.tourmarkers[i].title + '</h2>' +
'<br />' +
'<p>' +
'</p>';
infoWindow = new google.maps.InfoWindow({
content: content
});
var point = new google.maps.LatLng($scope.tourmarkers[i].lat, $scope.tourmarkers[i].lon);
markers = new google.maps.Marker({
label: "S",
animation: google.maps.Animation.DROP,
position: point,
map: map,
info: content
});
//SCOPE: 'this' refers to the current 'markers' object, we pass in the info and marker
google.maps.event.addListener(markers, 'click', function () {
infoWindow.setContent(this.info);
infoWindow.open(map, this);
});
}
};
var myLatlng = new google.maps.LatLng(38.5602, -121.4241);
var NAPA_HALL_LAT_LNG = new google.maps.LatLng(38.553801, -121.4212745); // just created this marker for testing purposes
var mapOptions = {
center: myLatlng,
zoom: 18,
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl: true,
disableDefaultUI: true
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'SAC STATE'
});
var dest = new google.maps.Marker({
position: NAPA_HALL_LAT_LNG,
map: map,
title: 'NAPA HALL'
});
///////////////////Directions Display//////////////////////
var directionsDisplay = new google.maps.DirectionsRenderer;
var directionsService = new google.maps.DirectionsService;
//////////////////////////////////////////////////////////////////////////////////////////
//Goal of this function is to find closest marker to current location
//then to create directions to that marker.
//should be refreshed everytime in the onSuccess function
var closest = function (directionsService, directionsDisplay, marker, dest) {
var event;
function rad(x) {return x*Math.PI/180;}
function find_closest_marker( event ) {
var lat = event.latLng.lat();
var lng = event.latLng.lng();
var R = 6371; // radius of earth in km
var distances = [];
var shortest = -1;
for( i=0;i < $scope.tourmarkers.length; i++) {
content = '<h2>' + $scope.tourmarkers[i].title + '</h2>' +
'<br />' +
'<p>' +
'</p>';
infoWindow = new google.maps.InfoWindow({
var mlat = $scope.tourmarkers[i].position.lat();
var mlng = $scope.tourmarkers[i].position.lng();
var dLat = rad(mlat - lat);
var dLong = rad(mlng - lng);
var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(rad(lat)) * Math.cos(rad(lat)) * Math.sin(dLong/2) * Math.sin(dLong/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
distances[i] = d;
if ( shortest == -1 || d < distances[shortest] ) {
shortest = i;
}
}
alert(map.markers[shortest].title);
}
/////**directions feature should have the closest marker be the desitination//
directionsService.route({
origin: marker.position,
destination: dest.position, // i think the marker that should in here is shortest.
travelMode: google.maps.TravelMode.WALKING
}, function(response,status) {
if(status==google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
};
//////////////////////////////////////////////////////////////////////////////////////////
var onSuccess = function (position) {
marker.setPosition(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
directionsDisplay.setMap(map);
dest.setPosition(new google.maps.LatLng(38.553801, -121.4212745));
//dest.setPosition((closest(marker, $scope.tourmarkers)).position); // if you can get this line to work without commenting it out then you're set
closest(directionsService,directionsDisplay, marker,dest);
$scope.map = map;
//$scope.map.panTo(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
};
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
navigator.geolocation.watchPosition(onSuccess, onError, {
maximumAge: 3000,
timeout: 5000,
enableHighAccuracy: true
});
Everything in this project is working properly except that closest function. but even then i have already tested the directionservice and even that is working too. I just need help making the destination in the direction service to be the closest marker to current location.
i think this code is helpful for you i used this code in my project such that your requirement same as my requirement
in the below function 'data' means list of lat lng's from server
function initialize(data) {
size = 0;
counts = 0;
stops = data;
size = stops.length;
if (stops.length > 0) {
var map = new window.google.maps.Map(document
.getElementById("map"));
// new up complex objects before passing them around
var directionsDisplay = new window.google.maps.DirectionsRenderer(
{
suppressMarkers : true,
polylineOptions : {
strokeColor : "black"
}
});
var directionsService = new window.google.maps.DirectionsService();
Tour_startUp(stops);
window.tour.loadMap(map, directionsDisplay);
window.tour.fitBounds(map,stops);
/* if (stops.length > 1) */
window.tour.calcRoute(stops,directionsService,
directionsDisplay,size);
}
}
function Tour_startUp(stops) {
var stops=stops;
var counts=0;
if (!window.tour) window.tour = {
// map: google map object
// directionsDisplay: google directionsDisplay object (comes in empty)
loadMap: function (map, directionsDisplay) {
var myOptions = {
zoom:10,
center: new window.google.maps.LatLng(17.379818, 78.478542), // default to Hyderabad
mapTypeId: window.google.maps.MapTypeId.ROADMAP
};
map.setOptions(myOptions);
directionsDisplay.setMap(map);
},
fitBounds: function (map,stops) {
var bounds = new window.google.maps.LatLngBounds();
// extend bounds for each record
jQuery.each(stops, function (key, val) {
var myLatlng = new window.google.maps.LatLng(val.latitude, val.longitude);
bounds.extend(myLatlng);
});
map.fitBounds(bounds);
},
calcRoute: function (stops,directionsService, directionsDisplay,size) {
size=size;
var batches = [];
var itemsPerBatch = 10; // google API max = 10 - 1 start, 1 stop, and 8 waypoints
var itemsCounter = 0;
var wayptsExist = stops.length > 0;
var tempp=0;
while (wayptsExist) {
var subBatch = [];
var subitemsCounter = 0;
for (var j = itemsCounter; j < stops.length; j++) {
subitemsCounter++;
tempp++;
subBatch.push({
location: new window.google.maps.LatLng(stops[j].latitude, stops[j].longitude),
stopover: true
});
if (subitemsCounter == itemsPerBatch)
break;
}
itemsCounter += subitemsCounter;
batches.push(subBatch);
wayptsExist = itemsCounter < stops.length;
// If it runs again there are still points. Minus 1 before continuing to
// start up with end of previous tour leg
itemsCounter--;
}
// now we should have a 2 dimensional array with a list of a list of waypoints
var combinedResults;
var unsortedResults = [{}]; // to hold the counter and the results themselves as they come back, to later sort
var directionsResultsReturned = 0;
for (var k = 0; k < batches.length; k++) {
var lastIndex = batches[k].length - 1;
var start = batches[k][0].location;
//delay(600);
var end = batches[k][lastIndex].location;
// trim first and last entry from array
var waypts = [];
waypts = batches[k];
waypts.splice(0, 1);
waypts.splice(waypts.length - 1, 1);
var request = {
origin: start,
destination: end,
waypoints: waypts,
travelMode: window.google.maps.TravelMode.WALKING
};
(function (kk) {
directionsService.route(request, function (result, status) {
if (status == window.google.maps.DirectionsStatus.OK) {
var unsortedResult = { order: kk, result: result };
unsortedResults.push(unsortedResult);
//alert("count test");
directionsResultsReturned++;
if (directionsResultsReturned == batches.length) // we've received all the results. put to map
{
// sort the returned values into their correct order
unsortedResults.sort(function (a, b) { return parseFloat(a.order) - parseFloat(b.order); });
var count = 0;
for (var key in unsortedResults) {
if (unsortedResults[key].result != null) {
if (unsortedResults.hasOwnProperty(key)) {
if (count == 0) // first results. new up the combinedResults object
combinedResults = unsortedResults[key].result;
else {
// only building up legs, overview_path, and bounds in my consolidated object. This is not a complete
// directionResults object, but enough to draw a path on the map, which is all I need
combinedResults.routes[0].legs = combinedResults.routes[0].legs.concat(unsortedResults[key].result.routes[0].legs);
combinedResults.routes[0].overview_path = combinedResults.routes[0].overview_path.concat(unsortedResults[key].result.routes[0].overview_path);
combinedResults.routes[0].bounds = combinedResults.routes[0].bounds.extend(unsortedResults[key].result.routes[0].bounds.getNorthEast());
combinedResults.routes[0].bounds = combinedResults.routes[0].bounds.extend(unsortedResults[key].result.routes[0].bounds.getSouthWest());
}
count++;
}
}
}
directionsDisplay.setDirections(combinedResults);
var legs = combinedResults.routes[0].legs;
var summaryPanel = document.getElementById('directions_panel');
summaryPanel.innerHTML = '';
var totdist=0;
for (var i=0; i < legs.length;i++){
var markerletter = "A".charCodeAt(0);
var markerletter2= "B".charCodeAt(0)
markerletter += i;
markerletter2 += i;
markerletter = String.fromCharCode(markerletter);
markerletter2 = String.fromCharCode(markerletter2);
createMarker(directionsDisplay.getMap(),legs[i].start_location,legs[i].start_address,markerletter,size);//To display location address on the marker
var routeSegment = i + 1;
var point=+routeSegment+1;
summaryPanel.innerHTML += '<b>Route Segment: ' + routeSegment + '</b><br>';
summaryPanel.innerHTML += '<b>Point '+ routeSegment +' :</b>'+ ' ' +legs[i].start_address + ' <br> ';
summaryPanel.innerHTML += '<b>Point '+ point +' :</b>'+ ' '+legs[i].end_address + '<br>';
summaryPanel.innerHTML += '<b>Distance Covered '+' :</b>'+legs[i].distance.text + '<br><br>';
var test=legs[i].distance.text.split(' ');
var one=parseFloat(test[0]);
if(test[1]=="m"){
var one=parseFloat(test[0]/1000);
}
totdist=parseFloat(totdist)+parseFloat(one);
}
summaryPanel.innerHTML += '<b> Total Distance :'+totdist + 'km'+ '</b><br><br>';
var i=legs.length;
var markerletter = "A".charCodeAt(0);
markerletter += i;
markerletter = String.fromCharCode(markerletter);
createMarker(directionsDisplay.getMap(),legs[legs.length-1].end_location,legs[legs.length-1].end_address,markerletter,size);
}
}
});
})(k);
function delay(ms) {
ms += new Date().getTime();
while (new Date() < ms){}
}
}
}//calculate route end
};
}
//to show information on clicking marker
var infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50)
});
var icons = new Array();
icons["red"] = new google.maps.MarkerImage("mapIcons/marker_red.png",
// This marker is 20 pixels wide by 34 pixels tall.
new google.maps.Size(20, 34),
// The origin for this image is 0,0.
new google.maps.Point(0,0),
// The anchor for this image is at 9,34.
new google.maps.Point(9, 34));
function getMarkerImage(iconStr,size) {
counts++;
if(counts==size){
var markerimageLoc = "http://www.maps.google.com/mapfiles/ms/icons/blue.png";
counts = 0;
}else{
if (iconStr=="undefined") {
iconStr = "red";
var markerimageLoc = "http://www.maps.google.com/mapfiles/ms/icons/red.png";
}
else{
var markerimageLoc="http://www.google.com/mapfiles/marker"+ iconStr +".png";
// var markerimageLoc = "http://www.maps.google.com/mapfiles/ms/icons/red.png";
}
}
icons[iconStr] = new google.maps.MarkerImage(markerimageLoc,
// This marker is 20 pixels wide by 34 pixels tall.
new google.maps.Size(25, 34),
// The origin for this image is 0,0.
new google.maps.Point(0,0),
// The anchor for this image is at 6,20.
new google.maps.Point(9, 34));
return icons[iconStr];
}
// Marker sizes are expressed as a Size of X,Y
// where the origin of the image (0,0) is located
// in the top left of the image.
// Origins, anchor positions and coordinates of the marker
// increase in the X direction to the right and in
// the Y direction down.
var iconShadow = new google.maps.MarkerImage('http://www.google.com/mapfiles/shadow50.png',
// The shadow image is larger in the horizontal dimension
// while the position and offset are the same as for the main image.
new google.maps.Size(37, 34),
new google.maps.Point(0,0),
new google.maps.Point(9, 34));
// Shapes define the clickable region of the icon.
// The type defines an HTML <area> element 'poly' which
// traces out a polygon as a series of X,Y points. The final
// coordinate closes the poly by connecting to the first
// coordinate.
var iconShape = {
coord: [9,0,6,1,4,2,2,4,0,8,0,12,1,14,2,16,5,19,7,23,8,26,9,30,9,34,11,34,11,30,12,26,13,24,14,21,16,18,18,16,20,12,20,8,18,4,16,2,15,1,13,0],
type: 'poly'
};
function createMarker(map, latlng, label, character,size) {
var markerletter = character;
var size=size;
if (/[^a-zA-Z]/.test(character)) {
var markerletter = "undefined";
}
var contentString = '<b>' + label + '</b><br>';
var marker = new google.maps.Marker({
position : latlng,
map : map,
shadow : iconShadow,
icon : getMarkerImage(markerletter,size),
shape : iconShape,
title : label,
zIndex : Math.round(latlng.lat() * -100000) << 5
});
marker.myname = label;
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
return marker;
}
This javascript wont get the coordinates of the user
(this is a html, js and css application only)
(the area with Bold and Italic text, is the one supposed to get the coordinates from the client)
I have tried different soloutions, and they wont work, + it doesnt show the ones if the user is within 25km
center: new google.maps.LatLng(val(coords.latitude),val(coords.longitude)),
<script type="text/javascript">
var side_bar_html = "";
var gmarkers = [];
var map = null;
var markerclusterer = null;
function createMarker(latlng, name, html) {
var contentString = html;
var marker = new google.maps.Marker({
position: latlng,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
gmarkers.push(marker);
side_bar_html += '<a href="javascript:myclick(' + (gmarkers.length-1) + ')">' + name + '<\/a><br>';
}
function myclick(i) {
google.maps.event.trigger(gmarkers[i], "click");
}
function initialize() {
var myOptions = {
zoom: 8,
center: new google.maps.LatLng(val(coords.latitude),val(coords.longitude)),
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
google.maps.event.addListener(map, 'click', find_closest_marker);
downloadUrl("markers.xml", function(doc) {
var xmlDoc = xmlParse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var point = new google.maps.LatLng(lat,lng);
var id = markers[i].getAttribute("id");
var sted = markers[i].getAttribute("sted");
var html="<b>"+sted+"</b><br>"+id;
var marker = createMarker(point,sted+" "+id,html);
}
markerCluster = new MarkerClusterer(map, gmarkers);
document.getElementById("side_bar").innerHTML = side_bar_html;
});
}
var infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50)
});
function find_closest_marker( event ) {
var closestMarker = -1;
var closestDistance = Number.MAX_VALUE;
for( i=0;i<gmarkers.length; i++ ) {
var distance = google.maps.geometry.spherical.computeDistanceBetween(gmarkers[i].getPosition(),event.latLng);
if ( distance < closestDistance ) {
closestMarker = i;
closestDistance = distance;
}
}
map.setCenter(gmarkers[closestMarker].getPosition());
if (map.getZoom() < 16) map.setZoom(16);
google.maps.event.trigger(gmarkers[closestMarker], 'click');
}
</script>
You can user a simple JS function for that.
<script>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showLatLng);
} else {
alert("Geolocation is not supported by this browser.");
}
}
function showLatLng(location) {
alert("Latitude: " + location.coords.latitude +
"Longitude: " + location.coords.longitude);
}
</script>
Hope it helps
function popupDirections(marker) {
var infowindow = new google.maps.InfoWindow(
{
content:
'Hello World'
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
}
I write this function in order to show the information of place name, street number, or somethings else, but the problem is that I don't know how to get that information to display on the pop up. Any help would be appreciated.
may be you want to try this, this my code that have a element info windows from JSON. but if you only want to write your infowindow, just write it like as tag javascript. in my case, my element of info window, i get from database.
function initialize(){
var x = new Array();
var y = new Array();
var customer_name = new Array();
var cp_rayon_name = new Array();
var icon = new Array();
var photo = new Array();
var city = new Array();
var address = new Array();
var postal_code = new Array();
// posisi default peta saat diload
var petaoption = {
zoom: 5,
center: new google.maps.LatLng( -1.2653859,116.83119999999997),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var peta = new google.maps.Map(document.getElementById("map_canvas"),petaoption);
//bound
var allowedBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(7.449624,93.15033),
new google.maps.LatLng(-12.640338,144.830017)
);
var boundLimits = {
maxLat : allowedBounds.getNorthEast().lat(),
maxLng : allowedBounds.getNorthEast().lng(),
minLat : allowedBounds.getSouthWest().lat(),
minLng : allowedBounds.getSouthWest().lng()
};
var lastValidCenter = peta.getCenter();
var newLat, newLng;
google.maps.event.addListener(peta, 'center_changed', function() {
center = peta.getCenter();
if (allowedBounds.contains(center)) {
// still within valid bounds, so save the last valid position
lastValidCenter = peta.getCenter();
return;
}
newLat = lastValidCenter.lat();
newLng = lastValidCenter.lng();
if(center.lng() > boundLimits.minLng && center.lng() < boundLimits.maxLng){
newLng = center.lng();
}
if(center.lat() > boundLimits.minLat && center.lat() < boundLimits.maxLat){
newLat = center.lat();
}
peta.panTo(new google.maps.LatLng(newLat, newLng));
});
var infowindow = new google.maps.InfoWindow({
content: ''
});
// memanggil function untuk menampilkan koordinat
url = "json.php";
$.ajax({
url: url,
dataType: 'json',
cache: false,
success: function(msg){
for(i=0;i<msg.enseval.customer.length;i++){
x[i] = msg.enseval.customer[i].x;
y[i] = msg.enseval.customer[i].y;
customer_name[i] = msg.enseval.customer[i].nama_customer;
cp_rayon_name[i] = msg.enseval.customer[i].nama_rayon;
icon[i] = msg.enseval.customer[i].icon;
photo[i] = msg.enseval.customer[i].id_photo;
city[i] = msg.enseval.customer[i].city;
address[i] = msg.enseval.customer[i].address;
postal_code[i] = msg.enseval.customer[i].postal_code;
var point = new google.maps.LatLng(parseFloat(msg.enseval.customer[i].x),parseFloat(msg.enseval.customer[i].y));
var gambar_tanda = 'assets/images/'+msg.enseval.customer[i].icon+'.png';
var photo_cust ='<img src="assets/images/foto_cust/'+msg.enseval.customer[i].id_photo+'_1.jpg" style="width:200px;height:120px;"/>';
//var nm_cust = msg.enseval.customer[i].nama_customer;
//var nm_rayon = , msg.enseval.customer[i].nama_rayon;
var html = '<b>' + customer_name[i] + '</b><br/>'+city[i]+ ', '+address[i]+', '+postal_code[i]+'<br/>' + cp_rayon_name[i] + '<br/>' + photo_cust;
tanda = new google.maps.Marker({
position: point,
map: peta,
icon: gambar_tanda,
clickable: true
});
bindInfoWindow(tanda, peta, infowindow, html );
}
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
function bindInfoWindow(tanda, peta, infowindow, data) {
google.maps.event.addListener(tanda, 'click', function() {
infowindow.setContent(data);
infowindow.open(peta, tanda);
});
}
function reload(form){
var val=form.org_id.options[form.org_id.options.selectedIndex].value;
self.location='main_page_admin.php?cabang=' + val ;
}