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);
Related
I am using Google Maps API to allow customers to more accurately identify where their products should be delivered in a city where addresses are inaccurate.
I tried the answers here and here, but neither resolved the issue.
We place a moveable pin at the location the customer specifies, and then retrieve the GPS coordinates once the customer is satisfied with their placement and hits "continue".
The problem is that the retrieved coordinates are neither the original ones associated with the address nor the new ones associated with the last location of said pin.
function initMap() {
var latitude = -8.111735;
var longitude = -79.025550;
if(localStorage.getItem('dm-latitude')){
var latitude = localStorage.getItem('dm-latitude');
var longitude = localStorage.getItem('dm-longitude');
if(latitude!='' && longitude!=''){
$('.dm-clone-btn').addClass('dm-none');
$('.dm-oroginal-btn').removeClass('dm-none');
}else{
$('.dm-clone-btn').removeClass('dm-none');
$('.dm-oroginal-btn').addClass('dm-none');
}
}
$('#dm-latitude').val(latitude);
$('#dm-longitude').val(longitude);
var myLatLng = new google.maps.LatLng(latitude,longitude);
var mapOptions = {
zoom: 15,
center: myLatLng
}
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var markers = [];
var marker = new google.maps.Marker({
position: myLatLng,
draggable:true,
title: latitude+', '+longitude
});
markers.push(marker);
marker.setMap(map);
google.maps.event.addListener(map,'click',function(event) {
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
var marker = new google.maps.Marker({
position: event.latLng,
map: map,
draggable:true,
title: event.latLng.lat()+', '+event.latLng.lng()
});
markers.push(marker);
localStorage.setItem('dm-latitude',event.latLng.lat());
localStorage.setItem('dm-longitude',event.latLng.lng());
$('#dm-latitude').val(event.latLng.lat());
$('#dm-longitude').val(event.latLng.lng());
$('.dm-clone-btn').addClass('dm-none');
$('.dm-oroginal-btn').removeClass('dm-none');
});
google.maps.event.addListener(marker, 'dragend', function(event) {
markers.push(marker);
localStorage.setItem('dm-latitude',event.latLng.lat());
localStorage.setItem('dm-longitude',event.latLng.lng());
$('#dm-latitude').val(event.latLng.lat());
$('#dm-longitude').val(event.latLng.lng());
$('.dm-clone-btn').addClass('dm-none');
$('.dm-oroginal-btn').removeClass('dm-none');
} );
// Create the search box and link it to the UI element.
var input = document.getElementById('pac-input');
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());
});
// more details for that place.
searchBox.addListener('places_changed', function() {
console.log('search ma');
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function(place) {
if (!place.geometry) {
console.log("Returned place contains no geometry");
return;
}
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,
title: place.name,
map: map,
draggable:true,
position: place.geometry.location
}));
console.log(place.geometry);
localStorage.setItem('dm-latitude',place.geometry.viewport.Za.i);
localStorage.setItem('dm-longitude',place.geometry.viewport.Ua.i);
$('#dm-latitude').val(place.geometry.viewport.Za.i);
$('#dm-longitude').val(place.geometry.viewport.Ua.i);
$('.dm-clone-btn').addClass('dm-none');
$('.dm-oroginal-btn').removeClass('dm-none');
// console.log(place.geometry.viewport);
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
You are using undocumented properties: place.geometry.viewport.Za.i and place.geometry.viewport.Ua.i.
Don't do that (those property names can and do change).
I certainly wouldn't expect any property of the viewport to be related to the actual location of a place (they are likely the north east and south west corners of a bounding box associated with the place.
// more details for that place.
searchBox.addListener('places_changed', function() {
console.log('search ma');
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function(place) {
if (!place.geometry) {
console.log("Returned place contains no geometry");
return;
}
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,
title: place.name,
map: map,
draggable:true,
position: place.geometry.location
}));
console.log(place.geometry);
localStorage.setItem('dm-latitude',place.geometry.location.lat());
localStorage.setItem('dm-longitude',place.geometry.location.lng());
$('#dm-latitude').val(place.geometry.location.lat());
$('#dm-longitude').val(place.geometry.location.lng());
$('.dm-clone-btn').addClass('dm-none');
$('.dm-oroginal-btn').removeClass('dm-none');
// console.log(place.geometry.viewport);
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
I am creating a google map that has a list of locations and then I want the user to be able to enter their(any) address into the map. Once they enter their address, a new marker must show and the bounds of the map need to update to include the new location.
I've successfully been able to set the new location as a cookie and redraw the bounds of the map on load, however when I try and do this on the geocode input click, the new marker loads, but the bounds seem to only redraw around the new location.
How can I get the bounds to redraw on the input?
Dev site link: http://rosemontdev.com/google-maps-api/
Here is my code:
var locations = [
['Dripping Springs', 30.194826, -97.99839],
['Steiner Ranch', 30.381754, -97.884735],
['Central Austin', 30.30497, -97.744086],
['Pflugerville', 30.450049, -97.639163],
['North Austin', 30.41637, -97.704623],
];
var currentLocationMarker = "http://rosemontdev.com/google-maps-api/wp-content/themes/rm-theme/images/current.png";
var locationMarker = "http://rosemontdev.com/google-maps-api/wp-content/themes/rm-theme/images/pin.png";
function initMap() {
window.map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infoWindow = new google.maps.InfoWindow();
var bounds = new google.maps.LatLngBounds();
var geocoder = new google.maps.Geocoder();
document.getElementById('submit').addEventListener('click', function() {
geocodeAddress(geocoder, map);
});
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,
icon: locationMarker,
});
var circle = new google.maps.Circle({
map: map,
radius: 3000,
fillColor: '#2B98B0',
fillOpacity: 0.2,
strokeOpacity: 0.25,
});
circle.bindTo('center', marker, 'position');
bounds.extend(marker.position);
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infoWindow.setContent(locations[i][0]);
infoWindow.open(map, marker);
}
})(marker, i));
} //closing for locations loop
var locationValue = Cookies.get('rmLocationCookie-Place');
var longValue = Cookies.get('rmLocationCookie-Long');
var latValue = Cookies.get('rmLocationCookie-Lat');
currentLocationNewMarker = new google.maps.Marker({
position: new google.maps.LatLng(longValue, latValue),
map: map,
icon: currentLocationMarker,
});
bounds.extend(currentLocationNewMarker.position);
map.fitBounds(bounds);
} //closing initMap
function geocodeAddress(geocoder, resultsMap) {
var address = document.getElementById('address').value;
var infoWindow = new google.maps.InfoWindow();
geocoder.geocode({'address': address}, function(results, status) {
if (status === 'OK') {
var currentLocationData = [];
var bounds = new google.maps.LatLngBounds();
var currentLocationName = 'Current Location';
var currentLocationLong = results[0]['geometry']['bounds']['f']['b'];
var currentLocationLat = results[0]['geometry']['bounds']['b']['b'];
currentLocationData.push(currentLocationName, currentLocationLong, currentLocationLat);
//Location Value Entered
Cookies.set('rmLocationCookie-Place', address);
//Geocoded Long
Cookies.set('rmLocationCookie-Long', currentLocationLong);
//Geocoded Lat
Cookies.set('rmLocationCookie-Lat', currentLocationLat);
var locationValue = Cookies.get('rmLocationCookie-Place');
if(locationValue === undefined){
console.log('no cookie set');
$('#cookie-notice').html('Your location is not saved.');
}
else{
$('#cookie-notice').html('Your location is saved as ' + locationValue +'');
}
updatedCurrentLocationMarker = new google.maps.Marker({
position: new google.maps.LatLng(currentLocationLong, currentLocationLat),
map: map,
icon: currentLocationMarker,
});
bounds.extend(updatedCurrentLocationMarker.position);
map.fitBounds(bounds);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
Try this:
Keep track of the original bounds before each geocode.
Then once the geocode completes pan to the marker and get the new map bounds the.
The idea is then to union the old and new bounds together using the. Union method then use the result as tour new map boundary.
originalbounds.union(newbounds)
Here is the code which I'm using to display search-box inside Google map.
function setSearchbox(map) {
// Create the search box and link it to the UI element.
var input = document.getElementById('searchLocation');
var searchBox = new google.maps.places.SearchBox(input);
// Bias the SearchBox results towards current map's viewport.
map.addListener('bounds_changed', function () {
searchBox.setBounds(map.getBounds());
});
var markers = [];
// [START region_getplaces]
// 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;
}
// Clear out the old markers.
markers.forEach(function (marker) {
marker.setMap(null);
});
markers = [];
// 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(40, 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,
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
}
And the output is,
Is it possible to move the search result box to just above the search box (drop-up instead of drop-down)?
I've gone through lot of reference website, but no luck.
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);
}
I am using the Google Maps Javscript API :
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();
var image = {
url: places[0].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 the closest result
marker = new google.maps.Marker({
map: map,
icon: image,
draggable : true,
title: places[0].name,
position: places[0].geometry.location
});
$('#inputLocalisation').val(places[0].geometry.location);
markers.push(marker);
bounds.extend(places[0].geometry.location);
map.fitBounds(bounds);
});
This handler is triggered when the user searches a location. It creates a marker on the closest result.
I would like to return the marker to use it later in an other handler :
google.maps.event.addListener(marker,'dragend',function() {
$('#inputLocalisation').val(marker.getPosition());
});
This one is triggered when the marker is dragged, but I need the marker object. How can I access the previously created marker?
So you should be adding that event listener at the same time as you're creating the marker I assume?
In the event listener function you can refer to it using the keyword this.
marker = new google.maps.Marker({
map: map,
icon: image,
draggable : true,
title: places[0].name,
position: places[0].geometry.location
});
google.maps.event.addListener(marker,'dragend',function() {
$('#inputLocalisation').val(this.getPosition());
});