Related
I have a places autocomplete field that I'm using to have users give a location. The autocomplete form is working, but it is NOT biasing the location as I want. I have the following code:
function activatePlacesSearch() {
var input = document.getElementById('project-location-input');
var location = {lat: 53.2910591, lng: -6.1823276};
var radius = 1000;
var autocomplete = new google.maps.places.Autocomplete(input, location, radius);
google.maps.event.addListener(autocomplete, 'place_changed', function(e) {
const place = autocomplete.getPlace();
lat = place.geometry.location.lat();
lng = place.geometry.location.lng();
// draw the map
document.getElementById('new-project-map-div').style.display = 'block'
var map = new google.maps.Map(document.getElementById('new-project-map-div'), {
zoom: 15,
center: new google.maps.LatLng(lat, lng),
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
streetViewControl: false,
fullscreenControl:false,
disableDefaultUI: true,
});
// Set marker position
var myMarker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),
draggable: false
});
map.setCenter(myMarker.position);
myMarker.setMap(map);
});
}
I know that you can query as follows and it works:
https://maps.googleapis.com/maps/api/place/autocomplete/xml?input=20&location=53.2910591,-6.1823276&radius=5000&key=AIzaSyC8sJYstB5U0fi8UdiHHAlG4tHVDuX_e-o
I would like to accomplish this using my code, but I'm doing something wrong here.
One option would be to use the AutocompleteOption.bounds. If all you know is a location and a radius, you can create a circle and call getBounds on it (there is no documented way to bias the javascript autocomplete with a location and a radius).
var location = {lat: 53.2910591, lng: -6.1823276};
var radius = 1000;
var circle = new google.maps.Circle({
center: location,
radius: radius
});
var autocomplete = new google.maps.places.Autocomplete(input, {
bounds: circle.getBounds()
});
proof of concept fiddle
code snippet:
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
function activatePlacesSearch() {
var input = document.getElementById('project-location-input');
var location = {lat: 53.2910591, lng: -6.1823276};
var radius = 1000;
var circle = new google.maps.Circle({
center: location,
radius: radius
});
var autocomplete = new google.maps.places.Autocomplete(input, {bounds: circle.getBounds()});
google.maps.event.addListener(autocomplete, 'place_changed', function(e) {
const place = autocomplete.getPlace();
console.log(place);
lat = place.geometry.location.lat();
lng = place.geometry.location.lng();
// draw the map
document.getElementById('new-project-map-div').style.display = 'block'
var map = new google.maps.Map(document.getElementById('new-project-map-div'), {
zoom: 15,
center: new google.maps.LatLng(lat, lng),
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
streetViewControl: false,
fullscreenControl:false,
disableDefaultUI: true,
});
// Set marker position
var myMarker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),
draggable: false
});
map.setCenter(myMarker.position);
myMarker.setMap(map);
});
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#new-project-map-div {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
<div class="pac-card" id="pac-card">
<div id="pac-container">
<input id="project-location-input" type="text"
placeholder="Enter a location">
</div>
</div>
<div id="new-project-map-div"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places&callback=activatePlacesSearch"
async defer></script>
Take a look at this section in their docs: google places autocomplete location biasing. You may be able to take advantage of the strictbounds and components params.
If that doesn't get you any closer to what you're trying to accomplish, post a link to a CodeSandbox with your example and I can help you figure it out.
Cheers! 🍻
After doing some investigative work here's what I came up with.
It seems that unless you are displaying a map on the DOM (it can be positioned out of sight if you don't want to see it) then this doesn't work correctly.
Here's an example I found on JSFiddle
//snippet
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 39.742347, lng: -104.941121}, //Denver, CO
zoom: 12
});
And here's my CodeSandbox example using your sandbox and some pointers from the example above.
I'm trying to implement a marker on a map. I can verify that the map renders correctly at the right center and zoom, but the marker does not show up.
function initMap() {
var latLng = new google.maps.LatLng({{latLng.latitude}}, {{latLng.longitude}})
var mapOptions = {
center: latLng,
zoom: 14,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var marker = new google.maps.Marker({
position: latLng,
visible: true,
map: map
});
}
I've also tried the implementation of adding the marker directly using marker.setMap(map):
function initMap() {
var myLatlng = new google.maps.LatLng({{latLng.latitude}}, {{latLng.longitude}});
var mapOptions = {
zoom: 14,
center: myLatlng
mapTypeId: google.maps.MapTypeId.SATELLITE
}
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
});
// To add the marker to the map, call setMap();
marker.setMap(map);
}
Neither render a marker. I've noticed that even when I replace the handlebars values for latitude and longitude with numerical coordinates for testing, the marker still does not appear. Any help appreciated!
I'm testing in Chrome.
You need to use this syntax window.onload = function initMap() and you are not assigning the marker to the map marker.setMap(map);, try in this way:
window.onload = function initMap() {
//I just put some custom LatLng to make it work
var LatLng = new google.maps.LatLng(41.9026329,12.452200400000038);
var mapOptions = {
center: LatLng,
zoom: 14,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var marker = new google.maps.Marker({
position: LatLng,
map: map
});
marker.setMap(map);
};
Here you can find a working Plunker made with this code + css + html.
If you are doing it with some AngularJS, give a look at my answer to this Question by #Dorin.
Window.OnLoad W3Schools Documentation
Question Related to Window.OnLoad
If you have still some problems, just let me know.
I hope I've been helpful.
I have the following code that creates a marker on Google Maps:
function initializeMap() {
var lat = '-32.089608'; //Set your latitude.
var lon = '115.933216'; //Set your longitude.
var centerLon = lon - 0.0105;
var myOptions = {
scrollwheel: false,
draggable: false,
disableDefaultUI: true,
center: new google.maps.LatLng(lat, centerLon),
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//Bind map to elemet with id map-canvas
var map = new google.maps.Map(document.getElementById('map-canvas'), myOptions);
var marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(lat, lon),
});
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker);
});
infowindow.open(map, marker);
}
I would like to add custom text to the pointer above the default marker but I cannot work out how to do it. At the moment it displays a small empty box above the default marker. (I am unable to post an example image due to lack of reputation points.
I am not very experienced with coding so any help is appreciated.
Thank you
You only need add content into your infowindow:
var infowindow = new google.maps.InfoWindow({
content: 'abcxyz'
});
I doubt the standard library supports this.
But you can use the google maps utility library:
https://code.google.com/p/google-maps-utility-library-v3/wiki/Libraries#MarkerWithLabel
var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var myOptions = {
zoom: 8,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
var marker = new MarkerWithLabel({
position: myLatlng,
map: map,
draggable: true,
raiseOnDrag: true,
labelContent: "A",
labelAnchor: new google.maps.Point(3, 30),
labelClass: "labels", // the CSS class for the label
labelInBackground: false
});
The basics about marker can be found here:
https://developers.google.com/maps/documentation/javascript/overlays#Markers
Google Maps API v3 marker with label
You only need to edit your marker click event function as below.
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker);
infoWindow.setContent('abcdxyz'); // add this line to your existing code
});
With this you can deal with multiple infoWindow for multiple markers.
Also if you want to display contents on mouseover, then you can use title property of marker like:
var marker = new google.maps.Marker({
position: {lat:lat, lng:lng},
map: map,
title: 'abcXYZ' // this will be displayed on marker mousover
});
My main goal with the program in question is to generate a Google map that shows the location of a specific building.
Due to Google limitation reasons, I have generated and stored all latitudes and longitudes for all the buildings that I analyze in a MS SQL database(it is a real estate web site). Everytime one building is selected then I retreive its corresponding latitud and longitude and store it in two asp:Label's. I use a script in Javascript in order to process the latitud and longitud which are passed on via two asp:Label's. My problem is that for some reason the LatLng function does not seem to work property and my maps do not show the coordinates that they should. I think I may have a problem with the type of variable that LatLng is expecting. I have tried both, default string that is passed on and converting the variables to real type. Here is the script. Any help or suggestions are appreciated:
<script type="text/javascript">
(function () {
// Defining global variables
var map, geocoder, marker, infowindow, propertyaddress, selectedbuilding, maplatitude, maplongitude, buildinglatlng, latlng, myOptions;
function InitializeMap() {
//propertyaddress = '400 Alton Road, Miami Beach, FL 33139';
propertyaddress = document.getElementById('<%=lblselectedHiddenBuildingAddress.ClientID%>').innerText;
selectedbuilding = document.getElementById('<%=lblMainBuilding.ClientID%>').innerText;
//maplatitude = parseFloat(document.getElementById('<%=lblCoordinateLatitud.ClientID%>').innerText);
//maplongitude = parseFloat(document.getElementById('<%=lblCoordinateLongitud.ClientID%>').innerText);
maplatitude = document.getElementById('<%=lblCoordinateLatitud.ClientID%>').innerText;
maplongitude = document.getElementById('<%=lblCoordinateLongitud.ClientID%>').innerText;
buildinglatlng = new google.maps.LatLng(maplatitude, maplongitude);
//window.alert("Processed propertyaddress");
//latlng = new google.maps.LatLng(25.76804, -80.132743);
// Creating an object literal containing the properties
// we want to pass to the map
myOptions = {
zoom: 15,
center: new google.maps.LatLng(maplatitude, maplongitude),
//center: buildinglatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scaleControl: true,
streetViewControl: true,
disableDefaultUI: true,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
position: google.maps.ControlPosition.TOP_LEFT,
mapTypeIds: [
google.maps.MapTypeId.ROADMAP,
google.maps.MapTypeId.TERRAIN,
google.maps.MapTypeId.SATELLITE
]
},
navigationControl: true,
navigationControlOptions: {
position: google.maps.ControlPosition.TOP_LEFT
}
};
// Creating the map
map = new google.maps.Map(document.getElementById("map"), myOptions);
}
window.onload = InitializeMap;
})();
</script>
#
Added Code that Works but uses the geocoder
#
For instance the following code works perfectly but it uses the geocoder. Passing the variables is not a problem. There is something strange with LatLng and what it does with the variables passed. It does get the values with all the significant places though.
<script type="text/javascript">
(function () {
// Defining global variables
var map, geocoder, marker, infowindow, propertyaddress, selectedbuilding, maplatitude, maplongitude, buildinglatlng, latlng, myOptions;
function InitializeMap() {
//propertyaddress = '400 Alton Road, Miami Beach, FL 33139';
propertyaddress = document.getElementById('<%=lblselectedHiddenBuildingAddress.ClientID%>').innerText;
selectedbuilding = document.getElementById('<%=lblMainBuilding.ClientID%>').innerText;
//maplatitude = parseFloat(document.getElementById('<%=lblCoordinateLatitud.ClientID%>').innerText);
//maplongitude = parseFloat(document.getElementById('<%=lblCoordinateLongitud.ClientID%>').innerText);
maplatitude = document.getElementById('<%=lblCoordinateLatitud.ClientID%>').innerText;
maplongitude = document.getElementById('<%=lblCoordinateLongitud.ClientID%>').innerText;
buildinglatlng = new google.maps.LatLng(maplatitude, maplongitude);
//window.alert("Processed propertyaddress");
//latlng = new google.maps.LatLng(25.76804, -80.132743);
if (!geocoder) {
geocoder = new google.maps.Geocoder();
}
// Creating a GeocoderRequest object
var geocoderRequest = {
address: propertyaddress
}
geocoder.geocode(geocoderRequest, function (results, status) {
// Check if status is OK before proceeding
if (status == google.maps.GeocoderStatus.OK) {
// Center the map on the returned location
//map.setCenter(results[0].geometry.location);
// Creating an object literal containing the properties
// we want to pass to the map
myOptions = {
zoom: 15,
//center: new google.maps.LatLng(maplatitude, maplongitude),
center: results[0].geometry.location,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scaleControl: true,
streetViewControl: true,
disableDefaultUI: true,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
position: google.maps.ControlPosition.TOP_LEFT,
mapTypeIds: [
google.maps.MapTypeId.ROADMAP,
google.maps.MapTypeId.TERRAIN,
google.maps.MapTypeId.SATELLITE
]
},
navigationControl: true,
navigationControlOptions: {
position: google.maps.ControlPosition.TOP_LEFT
}
};
// Creating the map
map = new google.maps.Map(document.getElementById("map"), myOptions);
// Check to see if we've already got a Marker object
if (!marker) {
// Creating a new marker and adding it to the map
marker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP
});
google.maps.event.addListener(marker, 'click', toggleBounce);
}
// Setting the position of the marker to the returned location
marker.setPosition(results[0].geometry.location);
// Check to see if we've already got an InfoWindow object
google.maps.event.addListener(marker, 'click', function () {
if (!infowindow) {
// Creating a new InfoWindow
infowindow = new google.maps.InfoWindow();
}
// Creating the content of the InfoWindow to the address
// and the returned position
var content = '<h2>' + selectedbuilding + '</h2>';
//content += 'Lat: ' + results[0].geometry.location.lat() + '<br />';
//content += 'Lng: ' + results[0].geometry.location.lng();
// Adding the content to the InfoWindow
infowindow.setContent(content);
// Opening the InfoWindow
infowindow.open(map, marker);
});
// Triggering the click event
google.maps.event.trigger(marker, 'click');
};
});
}
function toggleBounce() {
if (marker.getAnimation() != null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE);
}
}
window.onload = InitializeMap;
})();
</script>
Regards,
Elias
Have you verified that maplatitude and maplongitude contain the values you expect (eg. with a debugger)?
Is there any correlation between the expected location and the actual location shown on the map (for example, if the building is at N21.7684, and the marker is placed at N21.0000, the decimal places may have been lost).
I just found a post from Google where they changed the LatLng function and now you have to CAST the two parameters with NUMBER(). They claim that people were passing strings to the LatLng function and that created unpredicatable results. So I have appended my new code with the changes ... It only took three days to find this fix!!!! :-( I wonder why more people are not running into this. Here is the code:
<script type="text/javascript">
(function () {
// Defining global variables
var map, geocoder, marker, infowindow, propertyaddress, selectedbuilding, maplatitude, maplongitude, buildinglatlng, latlng, myOptions;
function InitializeMap() {
//propertyaddress = '400 Alton Road, Miami Beach, FL 33139';
propertyaddress = document.getElementById('<%=lblselectedHiddenBuildingAddress.ClientID%>').innerText;
selectedbuilding = document.getElementById('<%=lblMainBuilding.ClientID%>').innerText;
//maplatitude = parseFloat(document.getElementById('<%=lblCoordinateLatitud.ClientID%>').innerText);
//maplongitude = parseFloat(document.getElementById('<%=lblCoordinateLongitud.ClientID%>').innerText);
maplatitude = document.getElementById('<%=lblCoordinateLatitud.ClientID%>').innerText;
maplongitude = document.getElementById('<%=lblCoordinateLongitud.ClientID%>').innerText;
buildinglatlng = new google.maps.LatLng(Number(maplatitude), Number(maplongitude));
//window.alert("Processed propertyaddress");
myOptions = {
zoom: 15,
center: new google.maps.LatLng(Number(maplatitude), Number(maplongitude)),
mapTypeId: google.maps.MapTypeId.ROADMAP,
scaleControl: true,
streetViewControl: true,
disableDefaultUI: true,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
position: google.maps.ControlPosition.TOP_LEFT,
mapTypeIds: [
google.maps.MapTypeId.ROADMAP,
google.maps.MapTypeId.TERRAIN,
google.maps.MapTypeId.SATELLITE
]
},
navigationControl: true,
navigationControlOptions: {
position: google.maps.ControlPosition.TOP_LEFT
}
};
// Creating the map
map = new google.maps.Map(document.getElementById("map"), myOptions);
// Check to see if we've already got a Marker object
if (!marker) {
// Creating a new marker and adding it to the map
marker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP
});
google.maps.event.addListener(marker, 'click', toggleBounce);
}
// Setting the position of the marker to the returned location
marker.setPosition(buildinglatlng);
// Check to see if we've already got an InfoWindow object
google.maps.event.addListener(marker, 'click', function () {
if (!infowindow) {
// Creating a new InfoWindow
infowindow = new google.maps.InfoWindow();
}
// Creating the content of the InfoWindow to the address
// and the returned position
var content = '<h2>' + selectedbuilding + '</h2>';
// Adding the content to the InfoWindow
infowindow.setContent(content);
// Opening the InfoWindow
infowindow.open(map, marker);
});
// Triggering the click event
google.maps.event.trigger(marker, 'click');
}
function toggleBounce() {
if (marker.getAnimation() != null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE);
}
}
window.onload = InitializeMap;
})();
</script>
I'm trying to make my google maps embed default to terrain view. Attached is my code that loads everything correctly except the map options where I set the default view to terrain. I have it set up to only limit the choices to only terrain but when you initially load the page it is on the default hybrid view.
var map, marker, latLngToPixel;
var middle_earth_MORADOR = new google.maps.LatLng(38, 0);
function initialize() {
var mapOptions = {
zoom: 2,
center: middle_earth_MORADOR,
backgroundColor: "#000",
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.TERRAIN]
},
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var locations = [
// PHP LOOP FOR FEATURED PROJECTS
];
map = new google.maps.Map(document.getElementById("map_canvas"),mapOptions);
var styledMapOptions = {
map: map,
name: "map"
}
var build = new google.maps.StyledMapType(styledMapOptions);
map.mapTypes.set('map', build);
map.setMapTypeId('map');
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
icon: 'http://staging.******.com/css/images/pin.png',
map: map,
});
marker.setAnimation(google.maps.Animation.DROP);
setTimeout(function(){ marker.setAnimation(null); }, 1750);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
window.location = "http://staging.******.com/projects/" + locations[i][4];
}
})(marker, i));
}
}
I think you can disable the default UI of map by setting the property disableDefaultUI to true, and then set in the options the TERRAIN as the mapTypeId as how I did it below:
function loadMap() {
var myLatlng = new google.maps.LatLng(lat,lan);
var myOptions = {
zoom: 3,
center: myLatlng,
disableDefaultUI: true,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById("map"), myOptions);
//code
}
const map = new window.google.maps.Map(document.getElementById('Map'), {
mapTypeId: 'terrain'
});