Show only markers in given radius - javascript

i trying to make an algorithm that show only markers in a given radius this is my code:
for( i = 0; i < markers.length; i++ ) {
d = google.maps.geometry.spherical.computeDistanceBetween(
new google.maps.LatLng(user_logged_in[0][0],user_logged_in[0][1]),
new google.maps.LatLng(markers[i][0], markers[i][1]));
var position = new google.maps.LatLng(markers[i][0], markers[i][1]);
var icon = {url:"http://".concat(markers[i][3]),
scaledSize: new google.maps.Size(20, 20), // scaled size
origin: new google.maps.Point(0,0), // origin
anchor: new google.maps.Point(0, 0) };
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][4].toString().concat(' ').concat(markers[i][5].toString()),
icon: icon,
url:'im:<sip:'+markers[i][6]+'>'
});
if(<?=$this->translate($this->layout()->is_super_admin)?>==0){
marker.setVisible(false);
$(document).ready(function() {
$('#select-distance').change(function() {
var e = document.getElementById("select-distance");
var value = parseInt(e.options[e.selectedIndex].value);
if(d < value){
marker.setVisible(true);
}else{
marker.setVisible(false);
}
circle.setRadius(value);
circle.bindTo('center', markerc, 'position');
find_closest_marker(value);
});
});
}
}
But when I test it, it works only for the last user in the given radius. For example, if I have 3 users with distances 2km, 3km, 1km and I select a radius of 5km I get only the user with 3 km!!! Thanks for help.

Make new object of each marker and use that object.
See Below:
//here use the var keyword and a new marker object
var marker[i] = new google.maps.Marker({
position: position,
map: map,
title: markers[i][4].toString().concat(' ').concat(markers[i][5].toString()),
icon: icon,
url:'im:<sip:'+markers[i][6]+'>'
});
if(<?=$this->translate($this->layout()->is_super_admin)?>==0){
marker[i].setVisible(false);
$(document).ready(function() {
$('#select-distance').change(function() {
var e = document.getElementById("select-distance");
var value = parseInt(e.options[e.selectedIndex].value);
if(d < value){
marker[i].setVisible(true);
}else{
marker[i].setVisible(false);
}
circle.setRadius(value);
circle.bindTo('center', markerc, 'position');
find_closest_marker(value);
});
});
You are using the same object each time so it is replacing previous one. That's why it is drawing only last one marker.

Related

Show multiple markers on Google Maps.

I'm using the following JavaScript code to display Google Maps in my ASP.Net website. With this code I have added Google Places search that suggests results/places as the user types. I am displaying properties based on the searched location. However, I would like to display markers of the searched properties as well. I found a solution here: http://www.dotnetbull.com/2013/06/multiple-marker-with-labels-in-google.html but considering my limited knowledge of JavaScript I wasn't able to integrate it with my existing code to display places search along with markers on Google Maps. If you could please help me get it working I'll be thankful.
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places"></script>
<script type="text/javascript">
function LoadGoogleMAP() {
//Gets value of latitude and longitude of the search location from txtLatitude and txtLongitude textboxes.
var lat = document.getElementById('<%=txtLatitude.ClientID%>').value;
var lon = document.getElementById('<%=txtLongitude.ClientID%>').value;
var myLatlng = new google.maps.LatLng(lat, lon)
var markers = [];
var mapOptions = {
center: myLatlng,
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP,
marker: true
};
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
// Create the search box and link it to the UI element.
var input = (document.getElementById('MainContent_txtSearch'));
map.controls[google.maps.ControlPosition.CENTER].push(input);
var searchBox = new google.maps.places.SearchBox((input));
// Listen for the event fired when the user selects an item from the
// pick list. Retrieve the matching places for that item.
google.maps.event.addListener(searchBox, 'places_changed', function () {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}
// For each place, get the icon, place name, and location.
markers = [];
var bounds = new google.maps.LatLngBounds();
for (var i = 0, place; place = places[i]; i++) {
var image = {
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.
var marker = new google.maps.Marker({
map: map,
icon: image,
title: place.name,
position: place.geometry.location
});
markers.push(marker);
bounds.extend(place.geometry.location);
}
map.fitBounds(bounds);
map.setZoom(15);
});
// current map's viewport.
google.maps.event.addListener(map, 'bounds_changed', function () {
var bounds = map.getBounds();
searchBox.setBounds(bounds);
});
}
</script>
Try this code from Official Google Doc:
function initialize() {
var markers = [];
var map = new google.maps.Map(document.getElementById('map-canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(-33.8902, 151.1759),
new google.maps.LatLng(-33.8474, 151.2631));
map.fitBounds(defaultBounds);
// Create the search box and link it to the UI element.
var input = /** #type {HTMLInputElement} */(
document.getElementById('pac-input'));
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var searchBox = new google.maps.places.SearchBox(
/** #type {HTMLInputElement} */(input));
// Listen for the event fired when the user selects an item from the
// pick list. Retrieve the matching places for that item.
google.maps.event.addListener(searchBox, 'places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}
// For each place, get the icon, place name, and location.
markers = [];
var bounds = new google.maps.LatLngBounds();
for (var i = 0, place; place = places[i]; i++) {
var image = {
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.
var marker = new google.maps.Marker({
map: map,
icon: image,
title: place.name,
position: place.geometry.location
});
markers.push(marker);
bounds.extend(place.geometry.location);
}
map.fitBounds(bounds);
});
// Bias the SearchBox results towards places that are within the bounds of the
// current map's viewport.
google.maps.event.addListener(map, 'bounds_changed', function() {
var bounds = map.getBounds();
searchBox.setBounds(bounds);
});
}
google.maps.event.addDomListener(window, 'load', initialize);

Google Maps v3: plot different sets of markers

I am trying to plot on a google map a set of fixed markers and a marker for the user position. For these two sets of markers I would like to use a different image for the marker, however something weird is happening: when loading the page, the "fixed" markers get plotted properly but then immediately one disappears (the last one in the array) and then the user position shows up. In addition, the first fixed location gets the user location marker image, and the user positioning marker gets the image of the fixed markers. Ideally, the locations in the array will be plotted entirely (all 4) and with red_dot.png image on the marker, and the user positioning with the bluedot_retina.png on the marker.
It's really strange and I am struggling figuring out what is the root cause. Appreciate any help with this issue. thanks!
<script>
var locations = [
['location a', 37.60756088, -122.42793323],
['location b', 37.759736, -122.426957],
['location c', 37.752950, -122.438458],
['location d', 37.763128, -122.457942]
];
var map;
var i;
var marker;
var google_lat = 37.757996;
var google_long = -122.404479;
var myLatlng = new google.maps.LatLng(google_lat, google_long);
//google.maps.visualRefresh = true;
function initialize() {
var mapOptions = {
zoom: 12,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var image_dot = new google.maps.MarkerImage(
'images/red_dot.png',
null, // size
null, // origin
new google.maps.Point( 8, 8 ), // anchor (move to center of marker)
new google.maps.Size( 8, 8 ) // scaled size (required for Retina display icon)
);
marker = new google.maps.Marker({
flat: true,
position: myLatlng,
icon: image,
optimized: false,
map: map,
visible: true,
title: 'I might be here'
});
setMarkers(map, locations);
} //initialize();
function setMarkers(map, locations) {
for (var i = 0; i < locations.length; i++) {
var beach = locations[i];
var myLatLng1 = new google.maps.LatLng(beach[1], beach[2]);
marker = new google.maps.Marker({
position: myLatLng1,
icon: image_dot,
map: map
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<script type="text/javascript">
var Tdata;
var image = new google.maps.MarkerImage(
'images/bluedot_retina.png',
null, // size
null, // origin
new google.maps.Point( 8, 8 ), // anchor (move to center of marker)
new google.maps.Size( 17, 17 ) // scaled size (required for Retina display icon)
);
var userMarker = new google.maps.Marker({icon: image});
//var userMarker = new google.maps.Marker({icon: 'images/bluedot_retina.png'});
$.ajax({
method : "GET",
url: "get_location.php",
success : function(data){
Tdata=JSON.parse(data);
// console.log(data.lat);
console.log(Tdata.lat);
myFunction();
}
});
function myFunction(){
var interval = setInterval(function() {
$.get("get_location.php", function(Tdata) {
var JsonObject= JSON.parse(Tdata);
google_lat = JsonObject.lat;
google_long = JsonObject.long;
console.log(google_lat, google_long);
// $('#data').html('google_lat, google_long');
myLatlng = new google.maps.LatLng(google_lat, google_long);
//marker.setPosition(myLatlng);
userMarker.setPosition(myLatlng);
userMarker.setMap(map);
//map.setCenter(myLatlng);
});
}, 1000);
}
</script>
marker is a global variable. You are using it for both all of your locations and your user's position marker. Don't do that, assign unique (or local) names to the two classes of markers.
var Tdata;
var userMarker = new google.maps.Marker({icon: URL/to/custom/icon/for/user});
$.ajax({
method : "GET",
url: "get_location.php",
success : function(data){
Tdata=JSON.parse(data);
// console.log(data.lat);
console.log(Tdata.lat);
myFunction();
}
});
function myFunction(){
var interval = setInterval(function() {
$.get("get_location.php", function(Tdata) {
var JsonObject= JSON.parse(Tdata);
google_lat = JsonObject.lat;
google_long = JsonObject.long;
console.log(google_lat, google_long);
// $('#data').html('google_lat, google_long');
myLatlng = new google.maps.LatLng(google_lat, google_long);
userMarker.setPosition(myLatlng);
userMarker.setMap(map);
map.setCenter(myLatlng);
});
}, 1000);
}

Add event listeners to several map markers

I have the following function to set the Markers.
function setMarkers(map, locations, contenido) {
// Add markers to the map
console.log(contenido);
// 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 image = {
url: '<?php echo Yii::$app->request->baseUrl."/images/pinrojo.png";?>',
// This marker is 20 pixels wide by 32 pixels tall.
size: new google.maps.Size(20, 32),
// The origin for this image is 0,0.
origin: new google.maps.Point(0,0),
// The anchor for this image is the base of the flagpole at 0,32.
anchor: new google.maps.Point(0, 32)
};
// 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 shape = {
coords: [1, 1, 1, 20, 18, 20, 18 , 1],
type: 'poly'
};
var objeto_contentString = {};
var objeto_infowindow = {};
var object_marker = {};
for (var i = 0; i < locations.length; i++) {
objeto_contentString['contentString' + i ] = contenido[i]["META"] + "<BR/>" + contenido[i]["VENTA"];
objeto_infowindow['infowindow' + i] = new google.maps.InfoWindow({
content: objeto_contentString['contentString' + i ]
});
var beach = locations[i];
var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
object_marker['marker' + i] = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image,
shape: shape,
title: beach[0],
zIndex: beach[3]
});
google.maps.event.addListener(object_marker['marker' + i], 'click', function() {
objeto_infowindow['infowindow' + i].open(map,object_marker['marker' + i]);
});
}
console.log(objeto_contentString);
}
I would like to know how to add an event listener to every marker, but how? Is there a way to dynamically add those element listeners? I heard about some closure, but not sure how to implement them. With the current code, it will add only a listener to the last element of the array in the loop.
GoogleMap allows you to add event listeners to multiple markers. However, your code above won't work due to the fact that you are reusing the marker variable for all different markers. What you should be doing is, assign a marker variable for each of your objects. Don't reuse object_marker for all items.
// var object_marker = {}; // DONT USE IT
var markerCollections = [];
var objeto_infowindow = [];
for (var i = 0; i < locations.length; i++) {
objeto_contentString['contentString' + i ] = contenido[i]["META"] + "<BR/>" + contenido[i]["VENTA"];
objeto_infowindow['infowindow' + i] = new google.maps.InfoWindow({
content: objeto_contentString['contentString' + i ]
});
var beach = locations[i];
var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
// One object marker per one entity
var object_marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image,
shape: shape,
title: beach[0],
zIndex: beach[3]
});
var onclick = function(objeto_infowindow,marker){
var obj = objeto_infowindow;
return function(){
obj.open(map,marker);
}
}
google.maps.event.addListener(object_marker, 'click', onclick(objeto_infowindow['infowindow' + i], object_marker) );
// Keep the marker for later clean up if required
markerCollections.push(object_marker);
}
Instead of marker object, create markerArray to keep track of markers.
var markerArray=[];
Then use for loop to add all markers in the array.
Then finally use another for loop to iterate through markerArray to add all the listeners:
for(var i=0;i<markerArray.length;i++){
markerArray[i].on("click",function(){...});
}

How to get opening hours from google places api

Here I have a code that works fine, so here is simple google places code that show me a places based on location and I add an label on every marker so:
http://jsbin.com/UqafeCI/4/edit - CODE and DEMO
Now I want to in label show opening time so I add to my code:
if (!!place.opening_hours.periods[1].open.time) open = place.opening_hours.periods[1].open.time;
and now my code looks like this:
google.maps.event.addListener(searchBox, 'places_changed', function() {
var places = searchBox.getPlaces();
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}
// For each place, get the icon, place name, and location.
markers = [];
var bounds = new google.maps.LatLngBounds();
for (var i = 0, place; place = places[i]; i++) {
var image = {
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)
};
//THIS CODE I ADD TO PREVIOUS CODE THAT WORK, so if there is open time to show in label
var open = 'No work time';
if (!!place.opening_hours.periods[1].open.time) open = place.opening_hours.periods[1].open.time;
// Create a marker for each place.
var marker = new MarkerWithLabel({
map: map,
icon: image,
title: place.name,
position: place.geometry.location,
labelContent: open,
labelClass: "labels", // the CSS class for the label
labelStyle: {opacity: 0.75},
labelAnchor: new google.maps.Point(22, 0)
});
markers.push(marker);
bounds.extend(place.geometry.location);
}
map.fitBounds(bounds);
});
So how I can show open time of an object on label if time exist???
UPDATE:
I try to add request and service.getDetails function but again I cant get opening_time:
CODE:
google.maps.event.addListener(searchBox, 'places_changed', function() {
var places = searchBox.getPlaces();
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}
// For each place, get the icon, place name, and location.
markers = [];
var bounds = new google.maps.LatLngBounds();
for (var i = 0, place; place = places[i]; i++) {
var image = {
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)
};
var request = {
reference: place.reference
};
service.getDetails(request, function(place, status) {
var open = null;
try{
open = place.opening_hours.periods[1].open.time;
}
catch(e){
open='No work time';
}
var otvoreno = place.openNow+"</br>"+place.name;
// Create a marker for each place.
var marker = new MarkerWithLabel({
map: map,
icon: image,
title: place.name,
position: place.geometry.location,
labelContent: open,
labelClass: "labels", // the CSS class for the label
labelStyle: {opacity: 0.75},
labelAnchor: new google.maps.Point(22, 0)
});
});
markers.push(marker);
bounds.extend(place.geometry.location);
}
map.fitBounds(bounds);
});
Use a try-catch-statement:
try{
open = place.opening_hours.periods[1].open.time;
}
catch(e){
open='No work time';
}
...otherwise you will get an error when any of following is undefined:
place.opening_hours
place.opening_hours.periods
place.opening_hours.periods[1]
place.opening_hours.periods[1].open
But however, the documentation seems to be misleading, it suggests that the returned results are placeDetails. But that's not the fact , you need a further request for each place to request the placeDetails(which will contain the opening_hours.periods, when available)

google map custom pointer not working

i have put the google map java script code in my site and it does not working.Here is the code
function map_initialize() {
var latlng = [
__lats_and_langs__
];
if (google.maps.BrowserIsCompatible()) {
var image = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=15|FF0000|000000",
new google.maps.Size(20, 34),
new google.maps.Point(0, 0),
new google.maps.Point(10, 34));
map = new google.maps.Map2(document.getElementById('salon_map'));
map.addControl(new google.maps.LargeMapControl3D());
map.addControl(new google.maps.MenuMapTypeControl());
map.setCenter(new google.maps.LatLng(0, 0), 0);
for (var i = 0; i < latlng.length; i++) {
var marker = new google.maps.Marker({
position: latlng[i],
map: map,
icon: image,
title: location[0],
zIndex: location[3]
});
//var marker = new google.maps.Marker(latlng[i]);
map.addOverlay(marker);
}
var latlngbounds = new google.maps.LatLngBounds();
for (var i = 0; i < latlng.length; i++) {
latlngbounds.extend(latlng[i]);
}
map.setCenter(latlngbounds.getCenter(), map.getBoundsZoomLevel(latlngbounds));
map.setZoom(12);
// put markers and custom icon ??
__marker_list__
}
}
// google.maps.Event.addDomListener(window, 'load', map_initialize);
google.maps.Event.addDomListener(window, 'unload', google.maps.Unload);
Url is : http://myshopsalon.com/find-a-shop-salon
The markers are there(you may have noticed the single marker in the top-left corner of the map, it's not 1 marker, all these markers are placed at this location)
Reason: you are using the Maps-Library V2, but you create the Markers with the arguments expected in V3.
In V2 the 1st expected argument is the LatLng, nothing else.
var marker = new google.maps.Marker(latlng[i],{/*markerOptions*/});
(I've ommitted the options, because you've done the same mistake with the icon )
To clarify: When you use V2, you must use the methods as described here: https://developers.google.com/maps/documentation/javascript/v2/reference

Categories

Resources