Google Maps v3: plot different sets of markers - javascript

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);
}

Related

What will make google maps api clusters not work correctly?

I am looking for help to understand why my customized google maps api map will not work with marker clusters. Below is the section of code I am using to coordinate markers on the map but I cannot get them to cluster.
With this map there is a marker that shows the user where they are and there are multiple markers with the setup as restaurant below (ex: theaters, shops, etc) to show users things around them and I am looking to get the restaurants to cluster together as well as other points that are similar but the clustering will not group.
<script>
if(output.restaurantmsg == "ok") {
var image = {
url: 'img/Mobs/FK.png',
// This marker is 20 pixels wide by 32 pixels high.
size: new google.maps.Size(35, 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)
};
var shape = {
coords: [1, 1, 1, 20, 18, 20, 18, 1],
type: 'poly'
};
var restaurantslist = new Array();
for (var i = 0; i < restaurantmaplistname.length; i++) {
restaurantslist[i] = new Array();
restaurantslist[i][0] = restaurantmaplistname[i];
restaurantslist[i][1] = parseFloat(restaurantmaplistlat[i]);
restaurantslist[i][2] = parseFloat(restaurantmaplistlng[i]);
restaurantslist[i][3] = i+1;
restaurantslist[i][4] = restaurantmaplistcontent[i];
}
//alert(dealslist);
for (var i = 0; i < restaurantslist.length; i++) {
var restaurantli = restaurantslist[i];
//alert(dealli[1]+'-'+dealli[2]+'-'+(typeof dealli[1])+'-'+typeof dealli[2]);
var markers = locations.map(function(lat: restaurantli[1], lng: restaurantli[2], ) {
var marker = new google.maps.Marker({
position: {lat: restaurantli[1], lng: restaurantli[2]},
map: map,
icon: image,
animation: google.maps.Animation.DROP,
shape: shape,
title: restaurantli[0],
zIndex: restaurantli[3]
});
var infowindow = new google.maps.InfoWindow();
var content = restaurantli[4];
google.maps.event.addListener(marker,'click', (function(marker,content,infowindow){
return function() {
infowindow.setContent(content);
infowindow.open(map,marker);
};
})(marker,content,infowindow));
return marker;
});
}
var markerCluster = new MarkerClusterer(map, markers, {
imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
});
}
var locations = [{
lat: restaurantli[1],
lng: restaurantli[2],
info: "marker 1"
}, ];
google.maps.event.addDomListener(window, "load", initMap);
</script>

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 API: use first user location to center the map

I am building a Google Maps based web app on which I plot a moving dot of the user location. I am fetching continuously the user location from a server and would like to use the current user location when loading the map to center the window around it, meaning, when the user loads the site, the map will be centered around the first lat/long fetched from the server but enable the user to pan the map afterwards without re-centering it around where the user is. I was able to keep the map centered constantly around the user location but can't figure out how to use the first fetched location to center the map during initialization. My code is below, any help would be greatly appreciated. Thanks!
<script>
var locations = [
['location a', 37.771678, -122.469357],
['location b', 37.768557, -122.438458],
['location c', 37.755121, -122.438973],
['location d', 37.786127, -122.433223]
];
var map;
var i;
var marker;
var google_lat = 37.722066;
var google_long = -122.478541;
var myLatlng = new google.maps.LatLng(google_lat, google_long);
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)
);
function initialize() {
var mapOptions = {
zoom: 12,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
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});
$.ajax({
method : "GET",
url: "get_location.php",
success : function(data){
Tdata=JSON.parse(data);
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;
myLatlng = new google.maps.LatLng(google_lat, google_long);
userMarker.setPosition(myLatlng);
userMarker.setMap(map);
//map.setCenter(myLatlng); --> this is not what I want since it will always keep the map centerd around the user
});
}, 1000);
}
</script>
Only set the map center the first time. One way of detecting the first time would be to create the "userMarker" the first time the data is loaded.
var userMarker;
$.ajax({
method : "GET",
url: "get_location.php",
success : function(data){
Tdata=JSON.parse(data);
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;
myLatlng = new google.maps.LatLng(google_lat, google_long);
if (!userMarker || !userMarker.setPosition) {
// create the marker
userMarker = new google.maps.Marker({
icon: image,
position: myLatlng,
map:map
});
// center the map the first time, when the marker is created
map.setCenter(myLatlng);
} else { // marker aleady exists
userMarker.setPosition(myLatlng);
}
});
}, 1000);
}
proof of concept fiddle

Setting the content for each marker Google Maps

Need a quick help with setting up the content for each marker that I'm creating
I'm looping through my Locations Obj that holds Lat,Lng for each marker (locationObj),
the content for each marker is been hold by other obejct (PermutationObj).
example:
locationObj-- > {"Lat":"34.163291","Lng":"-118.685123"} etc....
PermutationObj -- > ElectronicPopContent,LocationName
The thing is I'm getting for all the markers that I'm displaying on the map the first content and location name from the PermutationObj.
How can I fix it???
JS Code:
var locationObj;
var PermutationObj;
var map;
var mapOptions;
var shape = {
coord: [1, 1, 1, 20, 18, 20, 18, 1],
type: 'poly'
};
function setMap(locationList, permutation) {
// List of Lat,Lng
locationObj = $.parseJSON(locationList);
PermutationObj = $.parseJSON(permutation);
var qMapTypeId = google.maps.MapTypeId.SATELLITE
var LatLngCenter = new google.maps.LatLng(34.163291, -118.685123);
var mapOptions = {
zoom: 4,
center: LatLngCenter,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
}
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var bounds = new google.maps.LatLngBounds();
for (i in locationObj) {
var LatLngPair = new google.maps.LatLng(locationObj[i]["Lat"], locationObj[i]["Lng"]);
bounds.extend(LatLngPair);
map.fitBounds(bounds);
// for (j in PermutationObj) {
// // var image = PropObj[j]["ElectroincImageURL"];
// var content = PermutationObj[j]["ElectronicPopContent"];
// break
// }
var content = PermutationObj[i]["ElectronicPopContent"];
marker = new google.maps.Marker({
position: LatLngPair,
map: map,
draggable: false,
// icon: image,
shape: shape,
anchorPoint: new google.maps.Point(12, -25)
});
//Setting up the content of the info window dynamic wise.
var infowindow = new google.maps.InfoWindow({
content: content
});
//Setting up an event listener, When the user clicks the marker, an info window opens.
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(content);
infowindow.open(map, marker);
});
}
}
Changed a few things, the first is having only one instance of the InfoWindow, the other is storing the content as a marker property and use it on the click, the last is having an instance per marker by using var marker = ... instead of marker = ... Let me know if this works for you.
var locationObj;
var PermutationObj;
var map;
var mapOptions;
var infowindow = new google.maps.InfoWindow({ });
var shape = {
coord: [1, 1, 1, 20, 18, 20, 18, 1],
type: 'poly'
};
function setMap(locationList, permutation) {
// List of Lat,Lng
locationObj = $.parseJSON(locationList);
PermutationObj = $.parseJSON(permutation);
var qMapTypeId = google.maps.MapTypeId.SATELLITE
var LatLngCenter = new google.maps.LatLng(34.163291, -118.685123);
var mapOptions = {
zoom: 4,
center: LatLngCenter,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
}
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var bounds = new google.maps.LatLngBounds();
for (i in locationObj) {
var LatLngPair = new google.maps.LatLng(locationObj[i]["Lat"], locationObj[i]["Lng"]);
//Are you sure you need these 2 lines here?
bounds.extend(LatLngPair);
map.fitBounds(bounds);
var marker = new google.maps.Marker({
position: LatLngPair,
map: map,
draggable: false,
shape: shape,
anchorPoint: new google.maps.Point(12, -25),
infoWindowContent: PermutationObj[i]["ElectronicPopContent"]
});
//Setting up an event listener, When the user clicks the marker, an info window opens.
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(marker.infoWindowContent);
infowindow.open(map, marker);
});
}
}

open multiple infowindow from external click javascript

Hi i am using google map to show my search locations, below the map it lists the search result. wen the user clicks the below result the google map show the infowindow .
function setMarkers(map, locations)
{
var infoWindow = new google.maps.InfoWindow({});
var markers = new Array();
var image = new google.maps.MarkerImage('images/pin_red.png',
new google.maps.Size(32,39),
new google.maps.Point(0,0),
new google.maps.Point(18, 30));
var shape = {
coord: [1, 1, 1, 20, 18, 20, 18 , 1],
type: 'poly'
};
var alph = 65;
for (var i = 0; i < locations.length; i++) {
var beach = locations[i];
var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
var title = beach[0].split('~~');
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld='+String.fromCharCode(alph)+'|FF0000|000000',
shape: shape,
title: title[0]+'<br>'+title[1],
zIndex: beach[3]
});
$('#mappoint-'+String.fromCharCode(alph)).bind('click', function() {
google.maps.event.trigger(marker, 'mouseover')
});
google.maps.event.addListener(marker, 'mouseover', function() {
infoWindow.setContent(this.title);
infoWindow.open(map, this);
});
alph = parseInt(alph)+1;
}
}
This is the function i am using, it show the last created infowindow while clicking any result, anyone have any idea ?
$('#mappoint-'+String.fromCharCode(alph)).bind('click', function() {
google.maps.event.trigger(marker, 'mouseover')
});
This section having the problem, this binds only for last created marker .

Categories

Resources