(I'm very noob with this. I'm learning on my own, I know my code is messy.)
I am working with Google Maps API, and I want the user to click a button (either Restaurant 1 or Restaurant 2) and then have the map pan to the location of that restaurant, using a marker and a InfoWindow above. Simple, right?
Here's my HTML code so far.
<!DOCTYPE html>
<html>
<title>W3.CSS Template</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="estilo.css">
<link rel="stylesheet" href="fuente1.css">
<link rel="stylesheet" href="fuente2.css">
<style>
html,body,h1,h2,h3,h4,h5,h6 {font-family: "Roboto", sans-serif}
</style>
<body class="w3-light-grey">
<!-- Page Container -->
<div class="w3-content w3-margin-top" style="max-width:1400px;">
<!-- The Grid -->
<div class="w3-row-padding">
<!-- Left Column -->
<div class="w3-third">
<div class="w3-white w3-text-grey w3-card-4">
<div class="w3-container">
<img><br>Choose a restaurant<p><br>
<button id="button" style="width:110px;height:30px;cursor:pointer;">Restaurant 1</button>
<button id="button2" style="width:110px;height:30px;cursor:pointer;">Restaurant 2</button>
<!-- End Left Column --> </p>
</div>
</div>
</div>
<!-- Right Column -->
<div class="w3-twothird">
<div class="w3-container w3-card w3-white w3-margin-bottom">
<h2 class="w3-text-grey w3-padding-16"><i class="fa fa-suitcase fa-fw w3-margin-right w3-xxlarge w3-text-blue"></i>
MAP
</h2><div class="w3-container">
<html>
<body>
<div id="map" style="width:555px;height:500px"></div>
<script>
function myMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(31.825948, -116.599869),
zoom: 16
});
}
function addmarker(lat, lon) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lon),
map: map
});
map.panTo(new google.maps.LatLng(lat, lon));
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBQ3QnkneaUIsXaJHZtYwqdWxX9KCMj4CA&callback=myMap">"></script>
</body>
</html>
<br><br>
</div>
</div>
<!-- End Right Column -->
</div>
<!-- End Grid -->
</div>
<!-- End Page Container -->
</div>
</body>
</html>
</body>
</html>
As you can see I have everything set up. The only thing that doesn't work are the buttons.
I have the following Javascript but I have no idea whatsoever on how to implement it in my HTML.
$('#button').click(function() {
addmarker('-22.3157017', '-49.0660877');
});
$('#button2').click(function() {
addmarker('-23.5936152', '-46.5856465');
});
I'll be happy to hear any lectures for this affair and any help will be greatly appreciated.
For reference, I want it to work pretty much like this one. Place marker on google maps api with html button
I did not use your markup - I've created my own.
Upon checking your javascript, everything seems well, except of these two things: missing jQuery library and the code placement of your button event handlers.
It seems you are trying to add Google Maps Javascript API Markers to these locations "-22.3157017,-49.0660877" and "-23.5936152,-46.5856465" by pressing their corresponding triggers (buttons). I would suggest doing a Reverse Geocoding before adding the markers once an event has been fired.
The term geocoding generally refers to translating a human-readable
address into a location on a map. The process of doing the converse,
translating a location on the map into a human-readable address, is
known as reverse geocoding.
You should also add jQuery as an external library to make their events such as ".click()" to work. You can download it here.
For the buttons, you should add these lines $('#button1').click(function()); and $('#button1').click(function()); inside your myMap() function.
It should look something like this:
function myMap() {
var myLatLng = {lat: 31.825948, lng: -116.599869};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
$('#button1').click(function(){
var coord = { lat: parseFloat('-22.3157017'), lng: parseFloat('-49.0660877') };
addMarker( coord, map );
});
$('#button2').click(function(){
var coord = { lat: parseFloat('-23.5936152'), lng: parseFloat('-46.5856465') };
addMarker( coord, map );
});
}
On your addMarker function, add two arguments that accepts the coordinates, and the map object.
function addMarker(params, map) {);
Inside that function, create a variable geocoder and the value is a new instance of google.maps.Geocoder().
var geocoder = new google.maps.Geocoder();
With that, you can now use geocode method. Geocode method accepts two arguments: location and callback. In the location parameter, you need to supply the coordinates you acquired from the addMarker() function.
geocoder.geocode({'location' : params}, function( results, status ) {});
The callback is the part where most of our logic will be implemented. The callback accepts two arguments: results, and status. The results argument returns an array of results if the status is OK. If so, we will now iterate through each array element and then create a new Google Maps Javascript API Markers. On the markers, we'll just supply the coordinates and maps object for its position and map property.
if (status === 'OK') {
var result = results.map( function( value, index ){
map.setCenter(params);
var newMarker = new google.maps.Marker({
position : params,
map : map,
});
});
} else {
alert('Geo not successful: ' + status);
}
This line 'map.setCenter(params);' sets the position displayed by the map.
Whole code below:
<button id="button1">Restaurant 1</button>
<button id="button2">Restaurant 2</button>
<div id="map"></div>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCzjs-bUR6iIl8yGLr60p6-zbdFtRpuXTQ&callback=myMap">
</script>
function myMap() {
var myLatLng = {lat: 31.825948, lng: -116.599869};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
$('#button1').click(function(){
var coord = { lat: parseFloat('-22.3157017'), lng: parseFloat('-49.0660877') };
addMarker( coord, map );
});
$('#button2').click(function(){
var coord = { lat: parseFloat('-23.5936152'), lng: parseFloat('-46.5856465') };
addMarker( coord, map );
});
}
function addMarker(params, map) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'location' : params}, function( results, status ) {
if (status === 'OK') {
var result = results.map( function( value, index ){
map.setCenter(params);
var newMarker = new google.maps.Marker({
position : params,
map : map,
animation: google.maps.Animation.DROP,
});
});
} else {
alert('Geo not successful: ' + status);
}
});
}
Hope it could help and happy coding!
I have answered this before on stackoverflow for how to show icons and infowindow and just updated my fiddle to use https instead. Following are very simple steps you need to take care of.
When you click on that fiddle you will see all HTML, JS and CSS I have used to show icons on map, list of people on car and interactivity to click on them to centre on map.
Using gmap3 library I have inlcuded google map on page
Using List elements I have coded location of items at <li data-gb="car" data-mapid="sc102" data-isactive="0" data-lat="53.538566" data-long="-0.327017199999951">Second Car</li> in data attributes for each item. It can be restuarants, parks etc
Important bits in code are in Javascript and these are
Events and Addmarker actions as well as logic to click on list items.
{ action: 'addMarkers',
marker:{
values:ulmarkerspeople,
options:{
draggable: false,
icon:'http://webricate.com/stackoverflow/mapicons/male-2.png'
},
events:{
mouseover: function(marker, event, context){
var listelement = jQuery("li[data-mapid='"+context.data.id+"']");
jQuery(listelement).attr('style','background-color:#ccc');
jQuery(listelement).attr('data-isactive','1');
var map = $(this).gmap3("get"),
infowindow = $(this).gmap3({get:{name:"infowindow"}});
if (infowindow){
infowindow.open(map, marker);
infowindow.setContent(context.data.ht);
jQuery("#customPopup").html(context.data.ht);
jQuery("#customPopup").show(500);
} else {
$(this).gmap3({
infowindow:{
anchor:marker,
options:{content: context.data.ht}
}
});
jQuery("#customPopup").html(context.data.ht);
jQuery("#customPopup").show(500);
}
},
mouseout: function(marker,event,context){
var listelement = jQuery("li[data-mapid='"+context.data.id+"']");
jQuery(listelement).attr('style','background-color:#fff');
jQuery(listelement).attr('data-isactive','0');
var infowindow = $(this).gmap3({get:{name:"infowindow"}});
if (infowindow){
infowindow.close();
jQuery("#customPopup").hide(500);
jQuery("#customPopup").html("");
}
}
}
}
}
Please read through Javascript comments on fiddle and you will get the gist of it.
Related
Want to output the latitude and longitude of the marker point in the 2 input boxes below and then also save them but that can happen later. As the user drags around the marker, the latitude and longitude should keep updating. This is the code I have already:
Output
JS
HTML
Please help, I've tried to debug by adding the console.log but it isn't outputting anything which may suggest where the problem is. At least I can't see anything in Chrome dev tools. When I try to debug using Visual Studio breakpoints, none of it loads so I can't do it that way. I've tried a bunch of other stuff as well.
This is the javascript:
var map;
var marker = false;
function initMap() {
var centerOfMap = new google.maps.LatLng(51.487987, -0.237269); // St Paul's School
var options = {
center: centerOfMap,
zoom: 10
};
// extantiate a map object
map = new google.maps.Map(document.getElementById('map'), options);
marker = new google.maps.Marker({
position: centerOfMap,
map: map,
title: 'Drag me around',
draggable: true
});
google.maps.event.addListener(marker, 'dragend', function (event) {
markerLocation();
});
markerLocation();}
function markerLocation() {
// give the information back to the HTML
var currentLocation = marker.getPosition();
console.log(currentLocation.lat());
document.getElementById("lat").value = String.valueOf( currentLocation.lat());
document.getElementById("lng").value = String.valueOf( currentLocation.lng());
}
google.maps.event.addDomListener(window, 'load', initMap);
This is the HTML:
<div class="insert-location">
<p>Select a location where the task will be carried out. Click on a location to select it. Drag the marker to change it.</p>
<div id="map"></div>
<input type="text" id="lat" readonly="readonly"><br>
<input type="text" id="lng" readonly="readonly">
</div>
Ok, here is a working example of how I solved it (add you api key):
http://jsbin.com/rinayek/1/edit?html,css,js,output
1st replace this:
document.getElementById("lat").value = String.valueOf( currentLocation.lat());
document.getElementById("lng").value = String.valueOf( currentLocation.lng());
for this:
document.getElementById("lat").value = currentLocation.lat();
document.getElementById("lng").value = currentLocation.lng();
2nd make your <div id="map"> that is not children of <div class="insert-location">
For the rest you are ok, check the example for more clarity
I've just started trying to develop a website and I'd like to keep the html and javascript separate if I can. I'm trying to put a marker on a map, have the co-ordinates placed in a text box as part of a form, and have them sent to the database when the user submits the form. The code works when it's all inside the html doc, but when I try to separate it it doesnt work. Well, the map still shows up and I can set a marker on it, but it doesn't capture the co-ordinates.
In the head of the html
<script type="text/javascript" src="mapSubmitSighting.js"></script>
<body onload="initMap()">
Inside the div where I want the js to execute
<div id="map">
<div class="map" onclick="initMap();">
<script defer
src="https://maps.googleapis.com/maps/api/js?key==initMap"></script>
</div>
The js file
!function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: {lat: 54.621277, lng: -6.692649 }
});
google.maps.event.trigger(map, "resize");
map.addListener('click', function(e) {
placeMarkerAndPanTo(e.latLng, map);
});
}
!function placeMarkerAndPanTo(latLng, map) {
var marker = new google.maps.Marker({
position: latLng,
map: map
});
map.panTo(latLng);
document.getElementById("lat").value = latLng.lat();
document.getElementById("lng").value = latLng.lng();
}
I know there's lots wrong with this but if I could just work out how to get the javascript to work it'd be a start. Thank you!
Most part of your code actually works.
Did a few modification though.
Added initial marker position as I noticed that you intended to do this on your sample code.
Also, refactored your code so needed routines will be re-usable.
Please check below.
HTML
<!DOCTYPE html>
<html>
<head>
<style>
#map {
height: 400px;
width: 50%;
}
</style>
<script src="mapSubmitSighting.js"></script>
</head>
<body>
<div id="map"></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD72DV80rL8PBw2BTTWOwHV3NPSQdx24D8&callback=initMap"></script>
<br/>
<div>
Latitude: <input type="text" id="lat"/><br/><br/>
Longitude: <input type="text" id="lng"/>
</div>
</body>
</html>
JS
function initMap() {
var initialLocation = {lat: 54.621277, lng: -6.692649 };
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: initialLocation
});
var marker = setMarker(initialLocation, map);
setTextCoordinates(initialLocation.lat, initialLocation.lng);
google.maps.event.trigger(map, "resize");
map.addListener('click', function(e) {
placeMarkerAndPanTo(e.latLng, map);
});
}
function placeMarkerAndPanTo(latLng, map) {
var marker = setMarker(latLng, map);
map.panTo(latLng);
setTextCoordinates(latLng.lat(), latLng.lng());
}
function setMarker(latLng, map){
var marker = new google.maps.Marker({
position: latLng,
map: map
});
return marker;
}
function setTextCoordinates(lat, lng){
document.getElementById("lat").value = lat;
document.getElementById("lng").value = lng;
}
Output
Hope this helps!
You are probably not linking the file correctly.
You can open the developer tools (F12 in Chrome, or just right-click on some part of the page and select Inspect Element) and look at the errors in the console.
Most likely there's a 404 error. Look at the URL of the file, does it match the place where it is supposed to be? Are you missing a folder? Did you forget to upload it? Let us know so we can further assist!
You also do not need the ! in the beginning of your js function. This is preventing your html from reading the js file.
should look like -->
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,`enter code here`
my (cut down) code is as below. My markers are not showing up until I either click or move the map slightly... is there any way of getting around this so they show up instantly?
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>TSF - Labour Plan </title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"> </script>
<script type="text/javascript">
function initialize() {
var centerlatlng = new google.maps.LatLng(53.644638, -2.526855);
var myOptions = {
zoom: 6,
center: centerlatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var latlng = new google.maps.LatLng(51.752927, -0.470095);
var img = "https://dl.dropboxusercontent.com/u/55888592/tsf-logo.gif";
var info = "<img style = 'float: left' src='http://www.tsf.uk.com/wp-content/themes/default/images/tsf-logo.gif'><div style = 'float: right; width: 200px'><p><b>Job Number:</b> </p><p><b>Client:</b> ASDA</p><p><b>Location:</b> HEMEL HEMPSTEAD</p><p><b>Postcode:</b> HP2 4AA</p><p><b>Start Time:</b> 22:0</p><p><b>No of Men:</b> 10.0</p><p><b>Allocated Labour:</b> AB: 5.0, WK: 5.0, : , : , : , : </p><p><b>Job Information: </b>PICK UP TOOLS</div>";
var infowindow = new google.maps.InfoWindow({
});
var marker = new google.maps.Marker({
icon: img,
position: latlng,
map: map,
content: info
});
marker.setMap(map);
google.maps.event.addListener(marker, "click", function(content) {
infowindow.setContent(this.content);
infowindow.open(map,this);
});
}
google.maps.event.addDomListener(window, "load", initialize);
</script>
</head>
<body style="margin:0px; padding:0px;" onload="initialize()">
<div id="map_canvas" style="width: 100%; height: 100%;"></div>
</body>
</html>
It seems that the problem is still exists in google chrome in most recent version on google map api and marker cluster js.
So I'll post the code which helped in this issue for me.
google.maps.event.addListener(map, 'zoom_changed', function() {
setTimeout(function() {
var cnt = map.getCenter();
cnt.e+=0.000001;
map.panTo(cnt);
cnt.e-=0.000001;
map.panTo(cnt);
},400);
});
feel free to play with value of interval of 400 (in my case less than 400 woudn't fix problem, but higher value - higher lag time)
P.S.
make sure you have defined map variable:
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
I was struggling with the EXACTLY same problem and was so glad to hear other guys have the same problem. I experienced the problem with GMaps V3 in Safari and Firefox as well. I tried your solution and it works for me as well but I used the idle event instead the timeout:
google.maps.event.addListener(map, 'idle', function(event) {
var cnt = map.getCenter();
cnt.e+=0.000001;
map.panTo(cnt);
cnt.e-=0.000001;
map.panTo(cnt);
});
Just add it on initializing Google Maps. There might come up another issue working with infowindows and circles bound to markers. In my case I can set the radius of the circle in the infobox. Jumping out of the input field (with or without changing the radius value) makes red-like markers blue. If you then zoom in/out the original color reappears. To solve this problem you have to change the zoom level quickly (in radius_changed event):
map.setZoom(map.getZoom()-1);
map.setZoom(map.getZoom()+1);
I've resolved this calling repaint on markerclusterer variable twice:
mc.repaint();
map.fitBounds(bounds); // for centering within the marker bounds
mc.repaint(); // repaint for getting it fixed
Hope this helps to anyone still facing the issue.
As per Geocodezips comment, this seems to be a local issue.
We use Google Map Api V3 to load google map in HTML container. We have a location search form. On submit, we will get the available locations and set markers in map. Once markers are loaded, on click on each marker we need to show Title, address details and design like what we have in google map. (In google maps - When clicking on red marker, we can see the more info overlay box with additional details like Stars, Directions, Search nearby, Save to Map, More..)
Do we have built in api function to load the overlay box like above. Or we don't have the function to load the details like what we have in google map currently.
When i searched in google and map docs, i can see options to show overlay window and write content inside the box. But i didn't see options to load the content as required.
I have pasted the code below for reference.
var map = null;
gmap_ready = function (){
var myLatlng = new google.maps.LatLng(43.834527,-103.564457);
var myOptions = {
zoom: 3,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
function fnLoadMarkers(){
var locations = [
['S Dakota', 43.834527,-103.564457, 1],
['Texas', 31.428663,-99.418947, 2],
['California', 36.668419,-120.249025, 3],
['Newyork', 43.197167,-76.743166, 4],
['Missouri', 38.410558,-92.73926, 5]
];
setMarkers(map,locations);
}
function setMarkers(map, locations) {
var image = 'images/marker.gif';
for (var i = 0; i < locations.length; i++) {
var currLocation = locations[i];
var latLng = new google.maps.LatLng(currLocation[1], currLocation[2]);
var marker = new google.maps.Marker({
position: latLng,
map: map,
icon: image,
title: currLocation[0],
zIndex: currLocation[3]
});
google.maps.event.addListener(marker, 'click', function() {
var latitude = this.position.lat();
var longitude = this.position.lng();
window.open("http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q="+latitude+","+longitude+"&sll="+latitude+","+longitude+"&sspn=0.172749,0.4422&ie=UTF8&ll="+latitude+","+longitude+"&spn=0.162818,0.4422&z=11&iwloc=A");
});
}
}
If there is any hint on how to achieve these results, it will be helpful. Also, please guide, whether it is possible through Google API V3.
Thanks in Advance,
Regards
Srinivasan.C
I don't understand why are you opening a new window to Google Maps from a Google Maps API marker?
You cannot add info window on Google Maps via URL.
This is how I do it.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
// Initiate map
function initialize(data) {
// Make position for center map
var myLatLng = new google.maps.LatLng(data.lng, data.lat);
// Map options
var myOptions = {
zoom: 10,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.HYBRID
};
// Initiate map
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
// Info window element
infowindow = new google.maps.InfoWindow();
// Set pin
setPin(data);
}
// Show position
function setPin(data) {
var pinLatLng = new google.maps.LatLng(data.lng, data.lat);
var pinMarker = new google.maps.Marker({
position: pinLatLng,
map: map,
data: data
});
// Listen for click event
google.maps.event.addListener(pinMarker, 'click', function() {
map.setCenter(new google.maps.LatLng(pinMarker.position.lat(), pinMarker.position.lng()));
map.setZoom(18);
onItemClick(event, pinMarker);
});
}
// Info window trigger function
function onItemClick(event, pin) {
// Create content
var contentString = pin.data.text + "<br /><br /><hr />Coordinate: " + pin.data.lng +"," + pin.data.lat;
// Replace our Info Window's content and position
infowindow.setContent(contentString);
infowindow.setPosition(pin.position);
infowindow.open(map)
}
</script>
</head>
<body onload="initialize({lat:-3.19332,lng:55.952366,text:'<h2>Edinburgh</h2><i>Nice city!</i>'})">
<div id="map_canvas">
</div>
</body>
</html>
I have multiple locations of my company's regional offices and have to show each location whenever user clicks at a locations like:
location1
location2
location3
When user clicks at location 1 it will show location 1 on the map. I also have those locations in my maps. I have never worked with Google maps before, so I just need some idea to get started.
When your user clicks a link, run a piece a javascript that calls setCenter(latlng:LatLng) on the map to center the map to a certain location.
If you really don't know where to begin, then start by reading the Google Maps API documentation. It's easy to read, and it contains lots of working examples.
You can do something like this: (I'm sure it could be optimized with a for loop, its early/late right now.
<html>
<head>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function initialize() { //Initalize JS after onload
var map = new google.maps.Map(document.getElementById('map_canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
});
var randomPoint1 = new google.maps.LatLng(44.6479, -63.5744); //First Location
var marker1 = new google.maps.Marker({ //Set up marker
position: randomPoint1,
map: map
});
google.maps.event.addDomListener(document.getElementById('locationid1'), 'click', //Set up DOM listener 1
function(){
map.setZoom(13);
map.setCenter(marker1.getPosition());
});
var randomPoint2 = new google.maps.LatLng(45.5081, -73.5550); //Second Location
var marker2 = new google.maps.Marker({
position: randomPoint2,
map: map
});
google.maps.event.addDomListener(document.getElementById('locationid2'), 'click',//Set up DOM listener 2
function(){
map.setZoom(13);
map.setCenter(marker2.getPosition());
});
var randomPoint3 = new google.maps.LatLng(43.6481, -79.4042); //Third Location
var marker3 = new google.maps.Marker({
position: randomPoint3,
map: map
});
google.maps.event.addDomListener(document.getElementById('locationid3'), 'click', //Set up DOM listener 3
function(){
map.setZoom(13);
map.setCenter(marker3.getPosition());
});
map.setCenter(marker2.getPosition());
map.setZoom(5);
}
</script>
</head>
<body onload="initialize()"> <!--Initalize JS after onload--->
Halifax
Montreal
Toronto
<div id="map_canvas" style="height:100%; width:100%"></div>
</body>
</html>
And after I write this I realize the post was from last August. Oh well, may help someone at some point.