1 Different Map Per Page Using Google Maps Javascript API - google-maps

I'm working on a site, and I'm looking to have 1 different Google Map on each page for a list of multiple pages. But I'm unsure as to how to go about this. I'm using a bit of code I found (Listed below.), on W3Schools, but the code they have is for one map on a single page, and multiple maps on a single page. I can't repeat the first function of Javascript even though I show it twice below, because it won't show up on other pages. There may be a way to rewrite it to get it to work, but I'm somewhat new to Javascript.
I've looked for this question, but couldn't come to find one relating to this, only how to create multiple maps per one html file.
I'm using this piece of Javascript on my main.js file rather than using the snippet on each separate page. This is a bit of code I found off of W3Schools. The only change I made was I copied and pasted the function and it's containing code twice -
function myMap() {
var mapCanvas = document.getElementById("map1");
var mapOptions = {
center: new google.maps.LatLng(51.508742,-0.120850),
zoom: 5
};
var map = new google.maps.Map(mapCanvas, mapOptions);
}
function myMap() {
var mapCanvas = document.getElementById("map2");
var mapOptions = {
center: new google.maps.LatLng(42.859822,-97.15901),
zoom: 5
};
var map = new google.maps.Map(mapCanvas, mapOptions);
}
And I'm using this piece of HTML on my first HTML page -
<div id="map1" style="width:100%;height:500px"></div>
And this one on my second -
<div id="map2" style="width:100%;height:500px"></div>
As found here on their website -http://www.w3schools.com/graphics/tryit.asp?filename=trymap_basic.
And as mentioned in the title I'm referencing the Google Maps Javascript API.
This is my structure to call the files I'm using, that I place on each HTML sheet.
<script type="text/javascript" src="js/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="js/main.js"></script>
<link href="https://fonts.googleapis.com/css?family=Cardo|Roboto:100,300,500" rel="stylesheet">
<script src="https://maps.googleapis.com/maps/api/js?callback=myMap"> </script>

You can only have one function with a given name in a scope. To load the map onto separate pages, if the <div> id is the same, you can use the same file with a single function in it:
main.js:
function myMap() {
var mapCanvas = document.getElementById("map");
var mapOptions = {
center: new google.maps.LatLng(51.508742,-0.120850),
zoom: 5
};
var map = new google.maps.Map(mapCanvas, mapOptions);
}
include it in the <body> of your pages like this:
<div id="map"></div>
<script type="text/javascript" src="scripts/SO_20170108_main.js"></script>
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=myMap"></script>
proof of concept/live example
page1.html
page2.html
common javascript

Related

Google map not working on web?

I am facing problem related to Google map. First time when page load It show google map but If I re-lode page again google map not shown on page.Any body have Idea about this problem.
Thanks.
You Can do this way :
<div id="map" style="width:400px;height:400px;background:yellow"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBu-916DdpKAjTmJNIgngS6HL_kDIKU0aU&callback=myMap"></script>
<script>
function myMap() {
var mapOptions = {
center: new google.maps.LatLng(51.5, -0.12),
zoom: 10,
}
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
}

Google Map layer refresh with Geojson

I am able to plot data onto google maps using geojson. I now want to refresh the markers every 10 seconds. How can I do this? In my example below the json file would refresh on my local server. How can I change the properties/ position of the same marker?
<!DOCTYPE html>
<html>
<head>
<style>
html, body, #map {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var map;
var layer1;
var layer2;
function initialize() {
var mapOptions = {
zoom: 11,
center: new google.maps.LatLng(23.0171240, 72.5330533),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);
layer1 = map.data.loadGeoJson('http://localhost/envitia.its.webclient/myjson.json');
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map">
</div>
</body>
</html>
Can you just use the setInterval() function in javascript? In you initialize() function, just wrap the layer1 command in a setInterval() with a time of 10 seconds.
I had a similar question and the comment from Todd is correct. Per the Google Maps API, the GeoJSON functions just load a bunch of features in into the map. To remove them, you can either
Remove every feature and start over
Implement some logic to remove only the features that need to be removed and selectively add ones not already on the map
It varies slightly if you use the .addGeoJson() function vs .loadGeoJson(). If you use the first one, you can do something like
if (mapFeatures != null) {
for (var i = 0; i < mapFeatures.length; i++) {
map.data.remove(mapFeatures[i]);
}
}
geoJSON = jQuery.parseJSON(json.data);
mapFeatures=map.data.addGeoJson(geoJSON);
mapFeatures is an array of Data.Feature objects which are just iterated and removed. If you use the .loadGeoJson() method instead, then you can use the forEach() method to iterate though the collection in the map object.
Have a look at the API reference. There is also a contains() method if you want to implement selective feature removal
https://developers.google.com/maps/documentation/javascript/reference#Data

Google Maps marker not showing

It's exactly the example code of the maps API documentation found here:
Google maps API documentation
I have set up an map and it is showing.
Next step was showing the marker with geocoding..
But it's not working? Can anyone help me out?
Thanks!!
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyAS1COH5SeJCKhZ6i6nTi0Fx2qsdvWbAfA&sensor=false"></script>
<script type="text/javascript">
var loMap;
var loGeocoder;
$(document).ready(function()
{
var loOptions =
{
center: new google.maps.LatLng(51.9645, 5.1965),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
loMap = new google.maps.Map(document.getElementById('map'), loOptions);
loGeocoder = new google.maps.Geocoder();
showMarkers();
});
function showMarkers()
{
console.log('World');
loGeocoder.geocode( { 'address': 'Den Bosch'}, function (results, status)
{
if(status == google.maps.GeocoderStatus.OK)
{
console.log('Hello?');
loMap.setCenter(results[0].geometry.location);
console.log(results[0].geometry.location);
var marker = new google.maps.Marker(
{
map: loMap,
position: results[0].geometry.location
});
}
else
{
console.log('Error');
}
});
}
</script>
<div id="map" class="search_map" style="width: 220px; height: 240px"></div>
An old question but as I recently hit the problem I thought I would share my solution. I found that something in the Javascript on the rest of my site was interfering with Google Maps. I was not getting any errors in Firebug or Chrome Console so I could not track down exactly what the conflict was.
I found that if I put the Google Map onto a blank ASPX page (i.e. no MasterPage with all of the Javascript and CSS from the rest of my site) that it worked fine.
The solution? I put the Google Map into an Iframe and now it works just fine. If you inspect the source of the Google Map example code, they use an Iframe too so there must be something to that.
you need to change the line new google.maps.LatLng(51.9645, 5.1965) to
var place = new google.maps.LatLng(51.9645, 5.1965);
and then use place as center in loOptions .
same as in marker also it really works :)
And import jquery as well
at the start of page.

Access KML Markers in Google Maps

Is there any way to create a "sidebar" from a KML file when using the Google Maps API?
I'm loading the markers on the map using something like this:
var myMarkerLayer = new google.maps.KmlLayer('http://example.com/WestCoast.kml');
This works great so far, but how can I grab that data and loop through the points?
I would like to avoid using a third party library, if possible- although jQuery is OK.
KML is just an XML document so you can just process it using jQuery to extract the data you need. You can store the coordinates and placenames in a local array and use this data for any purpose you want eg. you can use it to navigate to a point on the map when a person clicks on a place name on a sidebar.
Below is an example on how to process the KML file and implement the navigation based on the data in the file..One word of caution I would not do this with large KML files as it doubles the load time (browser has to load the file to process the features)...
<script type="text/javascript" src= "http://maps.google.com/maps/api/js?sensor=false">
</script>
<script src="../js/jquery-1.4.2.min.js">
</script>
<script>
var map;
var nav = [];
$(document).ready(function(){
//initialise a map
init();
$.get("kml.xml", function(data){
html = "";
//loop through placemarks tags
$(data).find("Placemark").each(function(index, value){
//get coordinates and place name
coords = $(this).find("coordinates").text();
place = $(this).find("name").text();
//store as JSON
c = coords.split(",")
nav.push({
"place": place,
"lat": c[0],
"lng": c[1]
})
//output as a navigation
html += "<li>" + place + "</li>";
})
//output as a navigation
$(".navigation").append(html);
//bind clicks on your navigation to scroll to a placemark
$(".navigation li").bind("click", function(){
panToPoint = new google.maps.LatLng(nav[$(this).index()].lng, nav[$(this).index()].lat)
map.panTo(panToPoint);
})
});
function init(){
var latlng = new google.maps.LatLng(-43.552965, 172.47315);
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), myOptions);
}
})
</script>
<html>
<body>
<div id="map" style="width:600px;height: 600px;">
</div>
<ul class="navigation">
</ul>
</body>
</html>
This isn't possible. Check the docs:
http://code.google.com/apis/maps/documentation/javascript/overlays.html#KMLLayers
Under "KML Feature Data":
Because KML may include a large number of features, you may not access feature data from the KmlLayer object directly. Instead, as features are displayed, they are rendered to look like clickable Maps API overlays.

Dynamically Loading Google Maps api's

Im trying to load the google maps api's dynamically.
I'm using the following code:
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.type= 'text/javascript';
script.src= 'http://www.google.com/jsapi?key=<MY_KEY>;
head.appendChild(script);
but when trying to create the map
map = new GMap2(document.getElementById("map"));
or
map = new google.maps.Map2(document.getElementById("map"));
I'm getting an error that google (or GMap2) is undefined.
You can do this. You can add a callback function name in the url. It'll be called when the API gets loaded. That callback function must be accessible in the document's scope.
I did that some time ago by triggering a custom event on the window with jQuery: http://jsfiddle.net/fZqqW/5/
used "http://maps.google.com/maps/api/js?sensor=false&callback=gMapsCallback"
window.gMapsCallback = function(){
$(window).trigger('gMapsLoaded');
}
$(document).ready((function(){
function initialize(){
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),mapOptions);
}
function loadGoogleMaps(){
var script_tag = document.createElement('script');
script_tag.setAttribute("type","text/javascript");
script_tag.setAttribute("src","http://maps.google.com/maps/api/js?sensor=false&callback=gMapsCallback");
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
}
$(window).bind('gMapsLoaded', initialize);
loadGoogleMaps();
})());​
Asynchronously Loading the API
You may wish to load the Maps API JavaScript code after your page has
finished loading, or on demand. To do so, you can inject your own
tag in response to a window.onload event or a function call,
but you need to additionally instruct the Maps JavaScript API
bootstrap to delay execution of your application code until the Maps
JavaScript API code is fully loaded. You may do so using the callback
parameter, which takes as an argument the function to execute upon
completing loading the API.
The following code instructs the application to load the Maps API
after the page has fully loaded (using window.onload) and write the
Maps JavaScript API into a tag within the page. Additionally,
we instruct the API to only execute the initialize() function after
the API has fully loaded by passing callback=initialize to the Maps
See HERE : https://developers.google.com/maps/documentation/javascript/tutorial
Make sure that you aren't instantiating the map before the Javascript has finished loading.
Also, If you want to use the AJAX API loader, you need to do it like this:
<script src="http://www.google.com/jsapi?key=ABCDEFG" type="text/javascript"></script>
<script type="text/javascript">
google.load("maps", "2.x");
// Call this function when the page has been loaded
function initialize() {
var map = new google.maps.Map2(document.getElementById("map"));
map.setCenter(new google.maps.LatLng(37.4419, -122.1419), 13);
}
google.setOnLoadCallback(initialize);
</script>
Otherwise, just use the regular Maps API script source:
<script src="http://maps.google.com/maps?file=api&v=2&key=abcdefg&sensor=true_or_false" type="text/javascript"></script>
I've done it like so... this example uses jQuery and google map v3.x
$.getScript("http://maps.google.com/maps/api/js?sensor=true&region=nz&async=2&callback=MapApiLoaded", function () {});
function MapApiLoaded() {
//.... put your map setup code here: new google.maps.Map(...) etc
}
This works for me:
const myApiKey = `12345`;
const lat = -34.397;
const lng = 150.644;
const zoom = 8;
const parentElement = document.getElementById(`map`); // a <div>
const script = document.createElement(`script`);
script.src = `https://maps.googleapis.com/maps/api/js?key=${myApiKey}`;
script.async = true;
script.defer = true;
script.onload = function () {
new google.maps.Map(parentElement, {
center: {lat, lng},
zoom
});
};
parentElement.insertBefore(script, null);