Javascript google maps - javascript

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.

Related

Trying to display latitude and longitude from Google API in JS to HTML

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

Can't get js function to load in html

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`

Markers not showing until map moved slightly or clicked

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.

Google Maps InfoWindow Not Popping Up When I Browse Back to Page

Using Google Maps Javascript V3, I have a map set up with some markers. I have a listener on each marker that pops up an InfoWindow on a click event. This works just fine. The problem is when I click on any link on the page and then browse back to the original page, the InfoWindows stop displaying. I have put in alert statements in the listener, so I know the listener is running, but I cannot figure out why the InfoWindows are not showing up.
Here is my code:
<script type="text/javascript">
var map;
var viewable;
var markerArray = new Array();
var infoWindow;
function initialize() {
infoWindow = new google.maps.InfoWindow({ content: "holding..." });
var mapOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoom: 15,
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var bounds = new google.maps.LatLngBounds();
var loop_latlng = new google.maps.LatLng( 42.341111, -71.080707 );
marker = addMarker( loop_latlng, "<strong>$1,495.00</strong> <br> Columbus Ave <br> 0 beds / 1 baths <br> <img src='/images/71428455_0.jpg' width=150> <br> <a href='/mls_rn/8305'>get more details</a>" );
bounds.extend(loop_latlng);
var loop_latlng = new google.maps.LatLng( 42.340022, -71.0657278 );
marker = addMarker( loop_latlng, "<strong>$2,000.00</strong> <br> Union Park St <br> 2 beds / 1 baths <br> <img src='/images/71426623_0.jpg' width=150> <br> <a href='/mls_rn/8253'>get more details</a>" );
bounds.extend(loop_latlng);
map.setCenter(bounds.getCenter());
map.fitBounds(bounds);
showMarkers();
}
function addMarker(location,contentString) {
var iw = new google.maps.InfoWindow({
content: contentString
});
var marker = new google.maps.Marker({
position: location,
animation: google.maps.Animation.DROP,
content: contentString,
map: map
});
google.maps.event.addListener(marker,'click',function(){
infoWindow.setContent(this.content);
infoWindow.open(map,this);
});
markerArray.push(marker);
return marker;
}
// display all the markers on the map
function showMarkers() {
if (markerArray) {
for ( i in markerArray ) {
markerArray[i].setMap(map);
}
}
}
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js?key=AIzaSyCICKRjJ3Vo_l2hy5uV7GdkYBot6jCtZzI&sensor=true&callback=initialize";
document.body.appendChild(script);
}
window.onload = loadScript;
</script>
I think this actually may be a Rails issue. If I cut and paste this into an HTML document, it seems to work just fine; however, within my Rails app, I'm seeing the off behaviour. The one thing I notice is that the maps seems to reinitialize in the pure HTML case, but doesn't seem to do so in Rails. I'll look into this more and comment. If anyone has seen this before; however, please chime in!
The behavior you describe doesn't happen for me on the official info windows samples, so i'd expect your code to behave the exact same way.
You would need to manually program for such functionality. On HTML5 compliant browsers, you can use the pageshow event to open the info window manually. However all current (less than 10.0) versions of Internet Explorer don't support the event so you would also have to handle this in the window load event.

Google Maps API V3 not rendering competely on tabbed page using Twitter's Bootstrap

I'm using Twitter's Bootstrap for defining my CSS. I have made a page with three tabs. The second tab contains a map built with Google Maps. However when opening the page and switching to the second page with the map, the map is not rendered completely. Once I reload the page with the google maps tab as the selected tab the map loads entirely.
I read some posts that advised people with the same problem to add the following code to the javascript:
google.maps.event.addDomListener(window, 'resize', function() {
map.setCenter(homeLatlng);
});
However this doesn't seem to be the solution. Please find the complete code below:
Javascript:
<script type="text/javascript">
function initialize() {
google.maps.event.addDomListener(window, 'resize', function() {
map.setCenter(homeLatlng);
});
var myLatlng = new google.maps.LatLng(37.4419, -122.1419);
var myOptions = {
zoom: 13,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
downloadUrl("data.xml", function(data) {
var markers = data.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var latlng = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var marker = new google.maps.Marker({position: latlng, map: map});
}
});
}
</script>
HTML:
<div class="tab-pane" id="orange" style="background-color:#E3F2FF;">
<div id="map_canvas" style="width:780px; height:400px; overflow:;"></div>
</div>
How can I resolve this? Maybe I can add some javascript that reloads the google maps part once the tab is selected but I don't know how to do this....
Updated code still shows the error:
<div class="tab-pane" id="orange" style="background-color:#E3F2FF;">
<div id="map_canvas" style="width:780px; height:400px; overflow:;"></div>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="util.js"></script>
<script type="text/javascript">
function initialize() {
google.maps.event.addDomListener(window, 'resize', function() {
map.setCenter(homeLatlng);
});
var myLatlng = new google.maps.LatLng(37.4419, -122.1419);
var myOptions = {
zoom: 13,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
downloadUrl("data.xml", function(data) {
var markers = data.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var latlng = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var marker = new google.maps.Marker({position: latlng, map: map});
}
});
map.checkResize();
}
</script>
</div>
I was battling with this issue as well. I was using a modal form and it rendered the map when it was hidden. When the tab is shown, you need to trigger this code:
google.maps.event.trigger(map, 'resize');
map.setZoom( map.getZoom() );
Hopefully it will work for you. If that doesn't work, here is the link where I found the solution. Maybe there will be another helpful comment.
http://code.google.com/p/gmaps-api-issues/issues/detail?id=1448
There's a lot of solutions here and frankly they're all wrong. If you have to hi-jack the default functionality of Bootstrap tabs, you might as well not use Bootstrap tabs. If you're only calling resize after the tab is shown, you may still have issues with the GMaps interface (zoom level and such). You simply have to initialize the map after the tab is visible.
var myCenter=new google.maps.LatLng(53, -1.33);
var marker=new google.maps.Marker({
position:myCenter
});
function initialize() {
var mapProp = {
center:myCenter,
zoom: 14,
draggable: false,
scrollwheel: false,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("map-canvas"),mapProp);
marker.setMap(map);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
};
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
initialize();
});
You can see a working example in this bootply: http://www.bootply.com/102241
Note: if your interface is still glitchy, it could be this issue:
Google Maps API V3 : weird UI display glitches (with screenshot)
Using the most recent gmaps api, you just need to add this to your styling:
.gm-style img { max-width: none; }
.gm-style label { width: auto; display: inline; }
Works for me after testing different delays :
$(window).resize(function() {
setTimeout(function() {
google.maps.event.trigger(map, 'resize');
}, 300)
});
Hope it helps.
I have solved the problem by using
google.maps.event.trigger(map, 'resize');
inside show function in bootstrap-tab.js means at the time of showing the box you should trigger resize event and will work..
Edit: I have seen another link with the same answer
Google Maps API v3, jQuery UI Tabs, map not resizing
I have seen this link after solving the problem to find out the reason which is still unanswered that why resize event does not works on the click event of the tabs but works in the tab js
this works fine for me, I use jquery tabs
setTimeout(function() {
google.maps.event.trigger(map, "resize");
map.setCenter(new google.maps.LatLng(default_lat, default_lng));
map.setZoom(default_map_zoom);
}, 2000);
from this link https://code.google.com/p/gmaps-api-issues/issues/detail?id=1448
To show a google maps in a hidden div, the div must show before the map is created and loaded. Below is an example:
<div id="map_canvas" style="width:500px; height:500px"></div>
<script>
$(document).ready(function(){
$('#button').click(function() {
$('#map_canvas').delay('700').fadeIn();
setTimeout(loadScript,1000);
});
});
function initialize() {
var title= "Title";
var lat = 50;
var lng = 50;
var myLatlng = new google.maps.LatLng(parseFloat(lat),parseFloat(lng));
var myOptions = {
zoom: 8,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
position: myLatlng,
title:artTitle
});
// To add the marker to the map, call setMap();
marker.setMap(map);
}
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=initialize";
document.body.appendChild(script);
}
</script>
For me, what it worked was to call the function that renders the map after the, in my case, the modal had shown.
All I had to do was:
$(document).on("shown", "#eventModal", function(){
bindMap(coordinates);
});
You can do the same with the tabs, because they also have a "shown" event.

Categories

Resources