I'm just starting json and google maps api using this video tutorial on youtube from 2013 as the example. I've got the demo map to display but it's giving me a
You have included the Google Maps API multiple times on this page. This may cause unexpected errors.
The original code didn't have an api key call, which I added, but I guess that calls the api twice. How do I not call the api twice?
<head>
<script src="https://maps.google.com/maps/api/js?sensor=false"></script>
<script>
// The web service URL from Drive 'Deploy as web app' dialog.
var DATA_SERVICE_URL = "https://script.google.com/macros/s/SPREADSHEET_ID/exec=?jsonp=callback";
var map;
function initialize() {
map = new google.maps.Map(document.getElementById('map_canvas'), {
center: new google.maps.LatLng(0, 0),
zoom: 2,
maxZoom: 20,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var scriptElement = document.createElement('script');
scriptElement.src = DATA_SERVICE_URL;
document.getElementsByTagName('head')[0].appendChild(scriptElement);
}
function callback(data) {
for (var i = 0; i < data.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data[i][3], data[i][2]),
map: map
});
}
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=#######&callback=jsonp"></script>
</head>
Oh, apparently the sensor parameter is no longer needed so I can just
<head>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=#######&callback=jsonp"></script>
<script>
// The web service URL from Drive 'Deploy as web app' dialog.
var DATA_SERVICE_URL = "https://script.google.com/macros/s/SPREADSHEET_ID/exec=?jsonp=callback";
var map;
function initialize() {
map = new google.maps.Map(document.getElementById('map_canvas'), {
center: new google.maps.LatLng(0, 0),
zoom: 2,
maxZoom: 20,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var scriptElement = document.createElement('script');
scriptElement.src = DATA_SERVICE_URL;
document.getElementsByTagName('head')[0].appendChild(scriptElement);
}
function callback(data) {
for (var i = 0; i < data.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data[i][3], data[i][2]),
map: map
});
}
}
</script>
</head>
Related
I'm trying to show directional points with poly line in google maps API but it creates a error. Anybody help to solve this problem.
Error: polyline-map.php:50 Uncaught ReferenceError: google is not defined
at polyline-map.php:50
<div id="map_canvas" style="height:400px; width:400px"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var map;
var polyline;
var markers = [ new google.maps.LatLng(17.43495, 78.50898333),
new google.maps.LatLng(17.43495, 78.50898333),
new google.maps.LatLng(17.43938333, 78.52168333),
new google.maps.LatLng(17.43708333, 78.52925),
new google.maps.LatLng(17.4366, 78.53336667)
];
function init() {
var directionsService = new google.maps.DirectionsService();
var moptions = {
center: new google.maps.LatLng(17.43938333, 78.52168333),
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), moptions);
var iconsetngs = {
path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW
};
var polylineoptns = {
strokeOpacity: 0.8,
strokeWeight: 3,
map: map,
icons: [{
repeat: '70px', //CHANGE THIS VALUE TO CHANGE THE DISTANCE BETWEEN ARROWS
icon: iconsetngs,
offset: '100%'}]
};
polyline = new google.maps.Polyline(polylineoptns);
var z = 0;
var path = [];
path[z] = polyline.getPath();
for (var i = 0; i < markers.length; i++) //LOOP TO DISPLAY THE MARKERS
{
var pos = markers[i];
var marker = new google.maps.Marker({
position: pos,
map: map
});
path[z].push(marker.getPosition()); //PUSH THE NEWLY CREATED MARKER'S POSITION TO THE PATH ARRAY
}
}
window.onload = init;
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=mykey&callback=init">
</script>
When you load the Google Maps Javascript API v3 asynchronously (async defer &callback=init), you can't use any of the google.maps namespace until it has loaded (when the callback function runs).
If you want to define the coordinates for your polyline outside of the init function, use LatLngLiteral anonymous objects:
Change:
var markers = [ new google.maps.LatLng(17.43495, 78.50898333),
new google.maps.LatLng(17.43495, 78.50898333),
new google.maps.LatLng(17.43938333, 78.52168333),
new google.maps.LatLng(17.43708333, 78.52925),
new google.maps.LatLng(17.4366, 78.53336667)
];
To:
var markers = [ {lat:17.43495,lng: 78.50898333},
{lat:17.43495,lng: 78.50898333},
{lat:17.43938333,lng: 78.52168333},
{lat:17.43708333,lng: 78.52925},
{lat:17.4366,lng: 78.53336667}
];
proof of concept fiddle
code snippet:
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px;
}
<div id="map_canvas"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var map;
var polyline;
var markers = [ {lat:17.43495,lng: 78.50898333},
{lat:17.43495,lng: 78.50898333},
{lat:17.43938333,lng: 78.52168333},
{lat:17.43708333,lng: 78.52925},
{lat:17.4366,lng: 78.53336667}
];
function init() {
var directionsService = new google.maps.DirectionsService();
var moptions = {
center: new google.maps.LatLng(17.43938333, 78.52168333),
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), moptions);
var iconsetngs = {
path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW
};
var polylineoptns = {
strokeOpacity: 0.8,
strokeWeight: 3,
map: map,
icons: [{
repeat: '70px', //CHANGE THIS VALUE TO CHANGE THE DISTANCE BETWEEN ARROWS
icon: iconsetngs,
offset: '100%'
}]
};
polyline = new google.maps.Polyline(polylineoptns);
var z = 0;
var path = [];
path[z] = polyline.getPath();
for (var i = 0; i < markers.length; i++) //LOOP TO DISPLAY THE MARKERS
{
var pos = markers[i];
var marker = new google.maps.Marker({
position: pos,
map: map
});
path[z].push(marker.getPosition()); //PUSH THE NEWLY CREATED MARKER'S POSITION TO THE PATH ARRAY
}
}
window.onload = init;
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=init">
</script>
I'm trying to use the traffic layer in the google maps API however when I try to initialize the TrafficLayer object using this line
var trafficLayer = new google.maps.TrafficLayer();
firebug throws this exception message for me
TypeError: ({oa:null}) is not a constructor
here's where I include the API
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
and here's where I initialize the map
function InitialRouteMapLoad(mapId,fromLon,fromLat,toLon,toLat) {
var fromlatlng = new google.maps.LatLng(fromLat, fromLon, true);
var tolatlng = new google.maps.LatLng(toLat, toLon, true);
bounds = new google.maps.LatLngBounds();
bounds.extend(fromlatlng);
bounds.extend(tolatlng);
var myOptions =
{
zoom: 12,
center: bounds.getCenter(),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById(mapId), myOptions);
bounds = new google.maps.LatLngBounds();
google.maps.event.addListener(map, 'click', function(e) {
});
geocoder = new google.maps.Geocoder();
ser = new google.maps.DirectionsService();
ren = new google.maps.DirectionsRenderer({ 'draggable': true });
ren.setMap(map);
debugger;
var trafficLayer = new google.maps.TrafficLayer();
trafficLayer.setMap(map);
}
Okay I found it
apparently unlike the other google maps API services I need to use an app key for that one
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&key={My Key}&sensor=false&libraries=places"></script>
In need of an example of how to show CAP (Common Alerting Protocol) location tags and areas from a feed (or file) on Google Maps. Currently I can show GeoRSS tags on Google Maps with this javascript code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="./jquery/jquery.zrssfeed.min.js" type="text/javascript"></script>
<script src="./jquery/jquery.vticker.js" type="text/javascript"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
function initialize() {
var myLatlng = new google.maps.LatLng(49.496675, -102.65625);
var mapOptions = {
zoom: 4,
center: myLatlng
};
var map = new google.maps.Map(document.getElementById('publicgeorss'), mapOptions);
var georssLayer = new google.maps.KmlLayer({
url: 'http://api.flickr.com/services/feeds/geo/?g=322338#N20&lang=en-us&format=feed-georss'
});
georssLayer.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize1);
And somewhere in the body:
<div id="publicgeorss" style="height:410px; width:400px"></div>
Thanks in advance.
It is straight forward. I dont know how you receive those CAP's, but if the format always is a you describe above you can use the following code :
(Have placed the CAP in a string variable, it would be the same from feed, ajax or file)
document.getElementById('show-cap').onclick = function() {
//parse CAP
var parser = new DOMParser(),
dom = parser.parseFromString(CAP, "text/xml"),
alert = dom.querySelector('alert');
//extract some data
var info = alert.querySelector('info'),
event = info.querySelector('event').textContent,
headline = info.querySelector('headline').textContent,
instruction = alert.querySelector('instruction').textContent,
latLngs = alert.querySelector('area').querySelector('polygon').textContent.split(',');
//create polygon
//CAP seems to have the polygon [1..length-1] and startpoint at [0,length]
var i, latLng,
start = new google.maps.LatLng(parseFloat(latLngs[0]), parseFloat(latLngs[latLngs.length-1])),
path = [start];
for (i=1;i<latLngs.length-1;i++) {
latLng = latLngs[i].split(' ');
path.push(new google.maps.LatLng(parseFloat(latLng[1]), parseFloat(latLng[0])));
}
new google.maps.Polygon({
paths: path,
fillColor: '#FF0000',
fillOpacity: 0.35,
strokeWeight: 0,
map: map
});
//find and set map center
var bounds = new google.maps.LatLngBounds();
for (i=0;i<path.length;i++) {
bounds.extend(path[i]);
}
map.setCenter(bounds.getCenter());
//create a marker
var marker = new google.maps.Marker({
position: bounds.getCenter(),
map: map
});
//create an infowindow with the headline and instructions
var info = new google.maps.InfoWindow({
content: '<h3>'+headline+'</h3>'+'<p>'+instruction+'</p>',
});
info.open(map, marker);
};
The result :
demo -> http://jsfiddle.net/wm5fsgas/
I am trying to add geo-location to a custom public google map, I can't manage to get it to work. For example here is a custom public google map.
Lets say I wanted to add geo-targeting to that map. I have the following on the site which is directly off the google maps API website:
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true"></script>
as well as the following which I just changed '.getElementsById' to '.getElementsByClassName':
<script type="text/javascript">
var map;
function initialize() {
var mapOptions = {
zoom: 3,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementsByClassName('map-canvas'),
mapOptions);
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Location found using HTML5.'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Then I call for the map which is in a lightbox:
<h2 class="dis">Where can I<br />get Rumble?</h2>
It displays the map fine, and asks to geo-target but I assume the reason its not working on this map is because its not included in the API.
I was hoping someone had a solution for this.
This is not an API based map. You can display the KML from that map on an API based map
Then use your geolocation code to center the map (depending on the ordering, you might need to use the preserveViewport:true option on the KmlLayer). Relevant code below, see the documenation for more examples and information.
This is in your existing page (leave your version)
var myOptions = {
zoom: 5,
center: new google.maps.LatLng(0,0),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
Add this to display the data from your "custom map":
var kmlLayer = new google.maps.KmlLayer("https://maps.google.ca/maps/ms?ie=UTF8&msa=0&output=kml&msid=202458571791405992786.0004b9061a3fcd9461d42");
kmlLayer.setMap(map);
I am having some difficulty with a google map. The problem is that only a small portion of the map is loading as shown here:
After the page loads, if I resize the browser even the slightest amount, this causes the complete map to refresh and load correctly, as shown here:
Here is my javascript code:
google.maps.event.addDomListener(window, 'load', initialize);
$(document).ready(function(){
var $width = document.getElementById("propertysection").offsetWidth;
$('#map-canvas-2').width($width-28-175);
$('#map-canvas-2').height($width);
$('#myGridMap').height($width);
});
function initialize() {
var map;
var propertyMap;
var marker;
var infowindow;
var myOptions = {
zoom: 6,
center:new google.maps.LatLng(50.7,-86.05),
mapTypeId: google.maps.MapTypeId.HYBRID
}
map = new google.maps.Map(document.getElementById("map-canvas-2"),myOptions);
infowindow = new google.maps.InfoWindow({
content: 'Property Info',
position: new google.maps.LatLng(0, 0)
});
}
Can anyone suggest what the problem might be? Thanks.
You shouldn't mix the jquery ready method with the window load event (see http://api.jquery.com/ready/).
Instead, call initialize from within your .ready function, or place the window resize functions in the initialize method itself (before initializing the map).
I am using bootstrap and a mega menu and I resolved it with using the official Google Maps API asynchronous load function. https://developers.google.com/maps/documentation/javascript/tutorial#asynch
function initialize() {
var myLatLng = new google.maps.LatLng(37.4221147, -122.0867373);
var map_canvas = document.getElementById('map_canvas');
var map_options = {
center: new google.maps.LatLng(37.4221147, -122.0867373),
zoom: 12,
mapTypeControl: false,
panControl: false,
zoomControlOptions: {
position: google.maps.ControlPosition.LEFT_CENTER
},
streetViewControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(map_canvas, map_options);
var contentString =
'<b>Google Gate Bridge</b>' +
'<p>Mountain View, CA 94043, USA</p>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
});
google.maps.event.addListener(marker, 'click', function(){
infowindow.open(map,marker);
});
}
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize";
document.body.appendChild(script);
}
var tab = document.getElementById('YourHtmlObjectID');
YourHtmlObjectID.onmouseover = loadScript;
YourHtmlObjectID.onclick = loadScript;