I have an input field where user enters the address. Google Maps API autocompletes it, and subsequently repositions map marker and is supposed to move the map to that location.
var map_location = new google.maps.LatLng(45.815015, 15.981912);
var marker;
var map;
var autocomplete;
function initialize() {
var mapOptions = {
zoom: 13,
center: map_location
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
marker = new google.maps.Marker({
map: map,
draggable: true,
position: map_location
});
google.maps.event.addListener(marker, 'dragend', function (event) {
document.getElementById("lat_hidden").value = this.getPosition().lat();
document.getElementById("long_hidden").value = this.getPosition().lng();
});
autocomplete = new google.maps.places.Autocomplete(
document.getElementById('autocomplete'),
{types: ['geocode']});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
map_location = new google.maps.LatLng(
parseFloat(document.getElementById("lat_hidden").value),
parseFloat(document.getElementById("long_hidden").value)
);
marker.setPosition(map_location);
map.panTo(map_location);
});
}
The last line of code causes infinite recursion. I also tried .setCenter. Firefox traced recursion to maps.gstatic.com script which keeps calling its own two functions.
What is causing the problem and how can I fix it?
You are not setting up the lat_hidden and long_hidden fields on the place_changed event. So this code doesn't create a valid google.maps.LatLng():
map_location = new google.maps.LatLng(
parseFloat(document.getElementById("lat_hidden").value),
parseFloat(document.getElementById("long_hidden").value)
);
working code snippet:
var map_location = new google.maps.LatLng(45.815015, 15.981912);
var marker;
var map;
var autocomplete;
function initialize() {
var mapOptions = {
zoom: 13,
center: map_location
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
marker = new google.maps.Marker({
map: map,
draggable: true,
position: map_location
});
google.maps.event.addListener(marker, 'dragend', function(event) {
document.getElementById("lat_hidden").value = this.getPosition().lat();
document.getElementById("long_hidden").value = this.getPosition().lng();
});
autocomplete = new google.maps.places.Autocomplete(
document.getElementById('autocomplete'), {
types: ['geocode']
});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
document.getElementById("lat_hidden").value = autocomplete.getPlace().geometry.location.lat();
document.getElementById("long_hidden").value = autocomplete.getPlace().geometry.location.lng();
map_location = new google.maps.LatLng(
parseFloat(document.getElementById("lat_hidden").value),
parseFloat(document.getElementById("long_hidden").value)
);
marker.setPosition(map_location);
map.panTo(map_location);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
height: 500px;
width: 500px;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<div id="map-canvas" style="width:750px; height:450px; border: 2px solid #3872ac;"></div>
<input id="lat_hidden" />
<input id="long_hidden" />
<input id="autocomplete" />
Related
This question already has answers here:
GoogleMaps v3 API Create only 1 marker on click
(5 answers)
Closed 5 years ago.
How to delete old markers and left only latest marker on google map.
I need only one marker no array.
Here is the code.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="map" style="width: 100%; height: 400px;"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAA3ATL-GNAlXBPYYBMjdjoNWKUWnJ9i-c"></script>
<script>
var map;
function initialize() {
var haightAshbury = new google.maps.LatLng(52.62440324134009, 4.88054275512695);
var mapOptions = {
zoom: 8,
center: haightAshbury,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'),
mapOptions);
google.maps.event.addListener(map, 'click', function(event) {
addMarker(event.latLng);
});
}
// Add a marker to the map and push to the array.
function addMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map
});
var lat = marker.getPosition().lat();
var lng = marker.getPosition().lng();
jQuery("#lat").val(lat);
jQuery("#lng").val(lng);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<div id="panel">
<input type="hidden" value="" name="lat" id="lat">
<br/>
<input type="hidden" value="" name="lng" id="lng">
If I understood you right you can make a click maker that appears on the map if you click it and changes the position if you click somewhere else:
var clickmarker = new google.maps.Marker({
draggable: false
});
google.maps.event.addListener(map, 'click', function(event) {
clickmarker.setPosition(event.latLng);
clickmarker.setMap(map);
clickmarker.setAnimation(google.maps.Animation.DROP);
var lat = clickmarker.getPosition().lat();
var lng = clickmarker.getPosition().lng();
jQuery("#lat").val(lat);
jQuery("#lng").val(lng)
});
So your code would be:
<script>
var map;
function initialize() {
var haightAshbury = new google.maps.LatLng(52.62440324134009, 4.88054275512695);
var mapOptions = {
zoom: 8,
center: haightAshbury,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'),
mapOptions);
var clickmarker = new google.maps.Marker({
draggable: false
});
google.maps.event.addListener(map, 'click', function(event) {
clickmarker.setPosition(event.latLng);
clickmarker.setMap(map);
clickmarker.setAnimation(google.maps.Animation.DROP);
var lat = clickmarker.getPosition().lat();
var lng = clickmarker.getPosition().lng();
jQuery("#lat").val(lat);
jQuery("#lng").val(lng)
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Here's the doc: https://developers.google.com/maps/documentation/javascript/examples/marker-remove
Seems you just need to remove all the markers before adding the new one and you're good.
You can just change coordinates of existing marker
var marker;
if (marker) {
marker.setPosition(location);
} else {
marker = new google.maps.Marker({
position: location,
map: map
});
}
I am creating a project using google map. My project contains hospital address ( in longitude and latitude) to be stored in database. But I want to show nearest hospital from my current location. And I am unable to figure out how to do it. Please help me with best algorithm and with some code.
Following code is used just to display all hospital address in map now I want is how to show only 3 nearest hospital from my current positiom.
function initMap() {
var mapType = google.maps.MapTypeId.ROADMAP;
var animationType = google.maps.Animation.DROP;
var currentLocationAnimationType = google.maps.Animation.BOUNCE;
var mapElement = document.getElementById('map');
var nepalLocation = {
lat: 28.3949,
lng: 84.1240
};
var mapOptions = {
center: nepalLocation,
zoom: 7,
mapTypeId: mapType,
};
// actual map
map = new google.maps.Map(mapElement, mapOptions);
var infoWindow = new google.maps.InfoWindow();
var latlngbounds = new google.maps.LatLngBounds();
var geocoder = geocoder = new google.maps.Geocoder();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(p) {
var LatLng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);
var marker = new google.maps.Marker({
position: LatLng,
map: map,
title: "My Location",
animation: currentLocationAnimationType
});
google.maps.event.addListener(marker, "click", function(e) {
var infoWindow = new google.maps.InfoWindow();
infoWindow.setContent(marker.title);
infoWindow.open(map, marker);
});
});
} else {
alert('Geo Location feature is not supported in this browser.');
}
for (var i = 0; i < markers.length; i++) {
var data = markers[i]
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
var image = "img/iconHospital.png";
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
icon: image,
title: data.district,
animation: animationType
});
}
}
google.maps.event.addDomListener(window, 'load', initMap);
<!DOCTYPE html>
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true&libraries=places"></script>
</head>
<body>
<div id="map"></div>
</body>
</html>
See this example at. I adapted your code accordingly.
function initMap() {
var mapType = google.maps.MapTypeId.ROADMAP;
var animationType = google.maps.Animation.DROP;
var currentLocationAnimationType = google.maps.Animation.BOUNCE;
var mapElement = document.getElementById('map');
var nepalLocation = {
lat: 28.3949,
lng: 84.1240
};
var mapOptions = {
center: nepalLocation,
zoom: 7,
mapTypeId: mapType,
};
// actual map
map = new google.maps.Map(mapElement, mapOptions);
var infoWindow = new google.maps.InfoWindow();
var latlngbounds = new google.maps.LatLngBounds();
var geocoder = geocoder = new google.maps.Geocoder();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(p) {
var LatLng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);
var marker = new google.maps.Marker({
position: LatLng,
map: map,
title: "My Location",
animation: currentLocationAnimationType
});
google.maps.event.addListener(marker, "click", function(e) {
var infoWindow = new google.maps.InfoWindow();
infoWindow.setContent(marker.title);
infoWindow.open(map, marker);
});
});
} else {
alert('Geo Location feature is not supported in this browser.');
}
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: nepalLocation,
radius: 50000,
type: ['hospital']
}, callback);
}
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
if (i == 2) {
break;
}
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
google.maps.event.addDomListener(window, 'load', initMap);
<!DOCTYPE html>
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true&libraries=places"></script>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
</body>
</html>
As per my question, I want to add an initial marker for the map, but it only shows me the marker when I enter address on load. If I want to show a marker like for longitude 41.008238 and latitude 28.978359, how can I make this possible? And sorry for my bad English.
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
<script>
function initialize() {
center: new google.maps.LatLng(41.008238, 28.978359),
zoom: 13
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
autocomplete = new google.maps.places.Autocomplete((document.getElementById('autocomplete')), {types: ['geocode']});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
var newPos = new google.maps.LatLng(place.geometry.location.lat(), place.geometry.location.lng());
map.setOptions({
center: newPos,
zoom: 15
});
var marker = new google.maps.Marker({
position: newPos,
map: map,
title:"market title"
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<div id="map-canvas">Loading map...</div>
<style>
#map {
/* float:right;*/
width: 100%;
height: 400px;
border: 1px solid #DDD;
}
#map-canvas {
width: 100%;
height: 350px;
}
</style>
add the following
var marker = new google.maps.Marker({
position: new google.maps.LatLng(41.008238, 28.978359),
map: map,
title: 'market title'
});
below
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var mapOptions = {
center: { lat: latitude, lng: longitude},
zoom: 10,
mapTypeId: google.maps.MapTypeId.HYBRID
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
google.maps.event.addListenerOnce(map, 'idle', function(){
//lat0 = map.getBounds().getNorthEast().lat();
//lng0 = map.getBounds().getNorthEast().lng();
//lat1 = map.getBounds().getSouthWest().lat();
//lng1 = map.getBounds().getSouthWest().lng();
get_markers();
});
function get_markers(){
marker = new google.maps.Marker({
position: new google.maps.LatLng(latit, longit,
map: map
});
}
I have written code to display a marker on a googlemap. The code is copied almost verbatim, from the Google API docs. Yet the marker is not displaying on the page.
Here is my code: What am I doing wrong?
var map;
var central_location = new google.maps.LatLng(42.745334, 12.738430);
function initialize() {
var mapCanvas = document.getElementById('map');
var mapOptions = {
center: central_location,
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(mapCanvas, mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
$(document).ready(function() {
var infowindow = new google.maps.InfoWindow({
content: '<div>Hello</div>'
});
var marker = new google.maps.Marker({
position: central_location,
map: map,
title: 'This is the title'
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
marker.setMap(map);
});
#map {
width: 500px;
height: 380px;
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript" style=""></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>
I notice that there are similar questions, the only thing that seems to be different with my question is that I am creating my marker in the jQuery ready() event - NOT the initialize() function.
Is this why the marker is not been displayed?
Note: I don't remember reading anything in the Google API docs that states that markers should be created when the map is being created, so that can't obviously be the case
Move your marker creation to the initialize function.
$(document).ready(function(){}) works when DOM elements are loaded, which doesn't necessarily mean that the map is loaded. So if you try to create the marker in the document ready function, the map might not be created then, once the map is ready map variable has the map object, so you can make the marker on that, and you can add the markers dynamically after the map is loaded.
var map;
var central_location = new google.maps.LatLng(42.745334, 12.738430);
function initialize() {
console.log('map loaded');
var mapCanvas = document.getElementById('map');
var mapOptions = {
center: central_location,
zoom: 14,
streetViewControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(mapCanvas, mapOptions);
makePin(42.745334, 12.738430);
}
google.maps.event.addDomListener(window, 'load', initialize);
$(document).ready(function(){
console.log('document loaded');
})
function makePin(lat, long){
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, long),
map: map,
title: 'This is the title'
});
var infowindow = new google.maps.InfoWindow({
content: '<div>Hello</div>'
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
}
#map {
width: 500px;
height: 380px;
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript" style=""></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<button onclick="makePin(42.749334, 12.739430)">Add Pin</button>
<div id="map"></div>
How can you make marker without loaded map. Map need to initialize first then marker will work
function initialize() {
var mapCanvas = document.getElementById('map');
var mapOptions = {
center: central_location,
zoom: 14,
streetViewControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(mapCanvas, mapOptions);
var marker = new google.maps.Marker({
position: central_location,
map: map,
title: 'This is the title'
});
marker.addListener('click', function () {
infowindow.open(map, marker);
});
marker.setMap(map);
}
Here is the solution:
var map;
var central_location = new google.maps.LatLng(42.745334, 12.738430);
function initialize() {
var mapCanvas = document.getElementById('map');
var mapOptions = {
center: central_location,
zoom: 14,
streetViewControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(mapCanvas, mapOptions);
var marker = new google.maps.Marker({
position: central_location,
map: map,
title: 'This is the title'
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
marker.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
$(document).ready(function() {
var infowindow = new google.maps.InfoWindow({
content: '<div>Hello</div>'
});
});
#map {
width: 500px;
height: 380px;
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript" style=""></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>
I have implemented the Google map successfully. But one more thing has left to do. I need to retrieve the Longitude and Latitude data when the user clicks on the map (any co-ordinates). My entire code looks like this:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var map;
function initialize() {
var myLatlng = new google.maps.LatLng(<?=$decimalValueLon?>,<?=$decimalValueLat?>);
var myOptions = {
zoom: 17,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
map = new google.maps.Map(document.getElementById('map_canvas'),
myOptions);
// marker STARTS
var marker = new google.maps.Marker({
position: myLatlng,
title:"Click to view info!"
});
marker.setMap(map);
// marker ENDS
// info-window STARTS
var infowindow = new google.maps.InfoWindow({ content: "<div class='map_bg_logo'><span style='color:#1270a2;'><b><?=$row->bridge_name?></b> (<?=$row->bridge_no?>)</span><div style='border-top:1px dotted #ccc; height:1px; margin:5px 0;'></div><span style='color:#555;font-size:11px;'><b>Length: </b><?=$row->bridge_length?> meters</span></div>" });
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
// info-window ENDS
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>`
Thanks in advance !
You can add a click-handler like you have a load handler:
google.maps.event.addListener(map, "click", function (e) {
//lat and lng is available in e object
var latLng = e.latLng;
});
<script>
var map;
function init_map() {
var opts = { 'center': new google.maps.LatLng(35.567980458012094,51.4599609375), 'zoom': 5, 'mapTypeId': google.maps.MapTypeId.ROADMAP }
map = new google.maps.Map(document.getElementById('mapdiv'), opts);
google.maps.event.addListener(map,'click',function(event) {
document.getElementById('latlongclicked').value = event.latLng.lat()
document.getElementById('lotlongclicked').value = event.latLng.lng()
});
google.maps.event.addListener(map,'mousemove',function(event) {
document.getElementById('latspan').innerHTML = event.latLng.lat()
document.getElementById('lngspan').innerHTML = event.latLng.lng()
});
}
google.maps.event.addDomListener(window, 'load', init_map);
</script>