I'm trying to migrate a simple Google Maps project (literally done from an example on their site) over to an AngularJS project. Let me preface this by saying that I'm new to both AngularJS and web dev, so please be kind :) I have a simple project up at https://github.com/eroth/angular-web-app (main files below) where I go from an initial commit using a Google Maps tutorial over to trying to convert it to an AngularJS app, but haven't been able to get it to work, although I've verified that my $scope.init() function in my MapController.js file is being called from my map.html file.
My question is two-fold: is it the case that something's wrong with my code, or do I need something like this (which looks to be very good): http://nlaplante.github.io/angular-google-maps/? I'm working on incorporating this into my project on another branch, but am trying to figure out if it's an issue with my existing code, or if I'd need something like this library to get it to work with AngularJS. If it's the latter, why? Apologizes in advance if it's some exceedingly simple mistake I'm making; as I said I'm pretty new to all this, although I did go through a few AngularJS tutorials and it seems great.
This is my map.html file:
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<!-- INCLUDE REQUIRED THIRD PARTY LIBRARY JAVASCRIPT AND CSS -->
<script type="text/javascript" src="js/angular.min.js"></script>
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/bootstrap-responsive.min.css">
<!-- INCLUDE APPLICATION SPECIFIC CSS AND JAVASCRIPT -->
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?sensor=true&language=en">
</script>
<script type="text/javascript" src="js/web-app/app.js"></script>
<script type="text/javascript" src="js/web-app/controllers/mainController.js"></script>
<link rel="stylesheet" href="css/main.css">
</head>
<body>
<div class="container main-frame" ng-app="WebApp" ng-controller ="mainController" ng-init="init()">
<div id="map-canvas"/>
</div>
</body>
</html>
And this is my MapController.js file:
app.controller("mainController", function($scope, $http){
$scope.initialLocation;
$scope.siberia = new google.maps.LatLng(60, 105);
$scope.newyork = new google.maps.LatLng(40.7463, -73.9913);
$scope.browserSupportFlag = new Boolean();
$scope.map;
$scope.retina = window.devicePixelRatio > 1;
$scope.init = function () {
var mapOptions = {
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
console.log('In main init');
//first test——map uses hard-coded location, next will get user's location and pull deals
$scope.map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
// Try W3C Geolocation (Preferred)
if (navigator.geolocation) {
$scope.browserSupportFlag = true;
navigator.geolocation.getCurrentPosition(function(position) {
$scope.initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var currentLat = position.coords.latitude;
var currentLon = position.coords.longitude;
$scope.map.setCenter($scope.initialLocation);
// performApiCall(currentLat, currentLon);
//definite custom map pin for user location & plot it on map
var pinColor = "5ea9ff";
var pinImage = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_spin&chld=0.6|0|" + pinColor + "|0|_|k",
new google.maps.Size(25, 60),
new google.maps.Point(0,0),
new google.maps.Point(10, 24));
var marker = new google.maps.Marker({
position: $scope.initialLocation,
map: $scope.map,
icon: pinImage,
});
}, function() {
handleNoGeolocation($scope.browserSupportFlag);
});
}
// Browser doesn't support Geolocation
else {
$scope.browserSupportFlag = false;
handleNoGeolocation($scope.browserSupportFlag);
}
function handleNoGeolocation(errorFlag) {
if (errorFlag == true) {
alert("Geolocation service failed.");
$scope.initialLocation = newyork;
} else {
alert("Your browser doesn't support geolocation. We've placed you in Siberia.");
$scope.initialLocation = siberia;
}
map.setCenter($scope.initialLocation);
}
};
google.maps.event.addDomListener(window, 'load', $scope.init);
});
Thanks in advance for any help!
There are a couple of things wrong with your code. First, you are already calling the init() function of your scope in your mainController via defining it in the DOM with ng-init.
<div class="container main-frame" ng-app="WebApp" ng-controller ="mainController" ng-init="init()">
Which means you do not need the listener for window to be loaded to call the $scope.init - because this would run the function twice and in turn initialize your map twice. Remove the listener.
Second, there are a few instances where variables are being called which are actually part of the $scope object (newyork Ln 57, serbia Ln 60 and map Ln 62) - hence will throw a not defined error.
And lastly, you must set a height for the div container of your map in the CSS to actually see the map.
#map-canvas { height : 200px; }
/* if you want to set the height as a percentage of the parent div, remember to give a height to the parent div as well */
As for the second part of your question, I would definitely look into using what's already built. I haven't used the library you linked to, but if you say it's very good - why try to re-invent the wheel?
Related
I am trying to create a map in node.js by calling my javascript file to do it for me.
require('./js/file.js')();
initMap();
This didn't work, as it gave me an error that "google was undefined" in my initMap() function. So, I tried to require the api script itself:
require('https://maps.googleapis.com/maps/api/js?key=APIKEY&libraries=places')();
require('./public/js/graphs.js')();
initMap();
which also, unsurprisingly, didn't work. How can I fix this? I tried loading in the map api inside the javascript file itself, but that required jquery, which also wasn't defined either, and so on.
You are trying to initialize the Google Maps JS which is designed for Browsers, not for Node, so that's why you get a "undefined" response.
I made this work by using PhantomJS; You create a "html template" where you have your map, initialize the map, then draw whatever you have to draw, and you can save it as PDF/Image with PhantomJS.
There is an example:
The "PhantomJS Script"
var page = require('webpage').create();
var system = require('system');
var args = system.args;
var fs = require('fs');
page.paperSize = {
format: 'A4',
orientation: 'portrait',
margin: '0mm'
};
var path = args[1];
var code = args[2];
page.open(path + '/imageMap.html', function(status) {
page.dpi = 96.0;
status = status.trim();
console.log(status);
if(status === "success") {
var title = page.evaluate(function(code) {
window.generateMap(code);
return true;
}, code);
setTimeout(function(){
page.render(path + '/img/' + code + '.png');
phantom.exit();
}, 1500);
}else{
phantom.exit(1);
}
});
As you can see, i give a 1500ms in the setTimeout, its just to make sure that the map was loaded and finished drawing (maybe there's a better way, but, it works)
And your imageMap.html is whatever you are doing with GMaps, like using the sample file from the docs:
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<style>
html, body {
width: 100%;
height: 100%;
margin:0px;
paddin:0px;
}
#map_canvas{
width:600px;
height: 445px;
}
.gm-style-cc {
display:none;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"
async defer></script>
</body>
</html>
I hope this helps somebody.
jQuery and other front end libraries don't work the same in nodejs. You'll want to look into a nodejs client for the google maps API.
This one is provided by google.
I have a feeling this is an obvious question, but it's stumping me and I'm not quite sure how to debug it. Probably just my javascript ignorance.
I'm using the leaflet utfgrid script from here: https://github.com/danzel/Leaflet.utfgrid
I'm mostly just following the example script, and I can't get the event handlers to work. At this point, I've got what I believe to be a very basic script. Here's the code - I'm looking to get the utfGrid.on('click') function to log to the console but it won't. I'd appreciate any help for feedback.
<head>
<meta charset="UTF-8">
<title>Leaflet Test</title>
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.0.3/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet#1.0.3/dist/leaflet.js"></script>
<script src="http://danzel.github.io/Leaflet.utfgrid/src/leaflet.utfgrid.js"></script>
<style>
#map{ width: auto; height: 800px; }
</style>
</head>
<body>
Map Data Test
<div id ="hover"></div>
<div id="map"></div>
<script>
// load a tile layer
var basemap = L.tileLayer('http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png', {attribution: 'CartoDB.', maxZoom: 18, minZoom: 2});
var cmamap = L.tileLayer('http://localhost:8080/tiles/{z}/{x}/{y}.png');
var utfGrid = new L.UtfGrid('http://localhost:8080/grid/{z}/{x}/{y}.json');
//event data
utfGrid.on('click', function (e) {
console.log('clicked');
});
//Create our map with just the base TileLayer
var map = L.map('map')
.setView([38, -94], 5)
.addLayer(basemap);
//Set up the base map and interactive stuff
var cmaLayers = L.layerGroup([
cmamap,
utfGrid
]).addTo(map);
</script>
</body>
So this looks like a version issue between the leaflet plugin and leaflet.utfgrid. When I use an old version of leaflet - it works.
I'm a newbie & this is my first post - pls forgive any protocol / formatting transgressions or the simplicity of my query - I could not find a conclusive solution elsewhere.
Problem
I'm trying to draw a map with little success - all I get is the grey box. Code is sourced from a combination of the Google API resource page and John Duckett's 'JavaScript & Jquery'.
Suspected Cause
My suspicion is its related to the API key, as I'm seeing no change in the API metrics on Google Developer - however, I'm not seeing any error in the Chrome console either.
Would appreciate any help - and how you identified the problem - thanks!
Code:
HTML:
<!DOCTYPE html>
<html>
<head>
<title>HR Sightings Page</title>
<link href='css/styles.css' type="text/css" rel="stylesheet" />
</head>
<body>
<div id="map-canvas"></div>
<script type="text/javascript" src="js/google-map.js"></script>
</body>
</html>
CSS - 'css/styles.css'
#map-canvas {
height: 500px;
margin: 0;
padding: 0;
}
JavaScript - 'js/google-map.js'
{//Initialisation function to set up map
function init() {
var mapOptions = { //Setup the map options
centre: new google.maps.LatLng(-24.939602, 31.578375), //specify map centre
mapTypeId: google.maps.MapTypeId.SATELLITE, //specify map type
zoom: 8 //set default zoom
};
var venueMap;
venueMap = new google.maps.Map(document.getElementById('map-canvas'),mapOptions); //draw the map
}
//Asyncronously load Google Maps api script once page is loaded
function loadScript() {
var script = document.createElement('script'); //create <script> element
script.type = 'text/JavaScript'
script.src = 'http://maps.googleapis.com/maps/api/js?' +
'key=AIzaSyBT5V-qRuEsNge9UDKsun74-Lf330Xlj7I&'+
'sensor=false&callback=init';
document.body.appendChild(script); //add element to the page
}
//load the script
window.onload = loadScript;}
You have typo in your code (bracket in a wrong place), change:
venueMap = new google.maps.Map(document.getElementById('map-canvas',mapOptions));
to:
venueMap = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
EDIT
I forgot one more typo to mention (centre should be center):
centre: new google.maps.LatLng(-24.939602, 31.578375),
should be:
center: new google.maps.LatLng(-24.939602, 31.578375),
Working example: http://js.do/nowa/62248
I want to edit all google maps from a page with an external js file.
Let's say that I have 5 pages with 3 google maps in every page.
I want to add a circle in every google map.
How to do this from an external javascript file which will be loaded in every page?
Your base page with multiple maps, and an external JS file:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
var maps = [];
function drawMaps(){
for(var i = 1; i<4;i++){
drawMap(i);
}
}
function drawMap(num){
var mapcontainer=document.getElementById("map"+num);
var options={
center: new google.maps.LatLng(40.266323, -73.996579),
zoom:8,
maptypeid:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(mapcontainer,options);
maps.push(map);
var circle=new google.maps.Circle({
map:map,
center:new google.maps.LatLng(40.266323, -73.996579),
radius:10000,
fillColor:"blue",
border:0,
strokeWeight:0
});
}
window.addEventListener("load", drawMaps);
</script>
<script src="externalJS.js"></script>
</head>
<html>
<body>
<div style="height:400px;width:400px" id="map1"></div>
<div style="height:400px;width:400px" id="map2"></div>
<div style="height:400px;width:400px" id="map3"></div>
</body>
</html>
Note the array which serves as an accessible bin for all maps. Also notice the window listener for "load."
The external JS file contents:
function addToAllMaps(){
if(maps!=undefined){
for (var i in maps){
var map = maps[i];
var circle=new google.maps.Circle({
map:map,
center:new google.maps.LatLng(40.266323, -73.996579),
radius:1000000,
fillColor:"red",
border:0,
strokeWeight:0
});
}
}
}
window.addEventListener("load", addToAllMaps);
Note how it references the maps array and applies the red circle to each in a loop. Also note the window listener for load. By using this event we can add multiple events, in the order the events were defined, in this case, the order in which scripts were loaded.
I am following the the steps given in this link
https://developers.google.com/maps/documentation/javascript/tutorial
I am getting error after load can you tell me where I wrong ? I already generate key ?
fiddle
http://jsfiddle.net/p3kcztvb/1/
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 100% }
</style>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyATC35pv00Ga3hRxP4t5W7NtM9as48PGVQs">
</script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 8
};
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"/>
</body>
</html>
Following error explain itself.
"provided key is not a valid Google API Key,"
Generate correct key
To create your API key:
Visit the APIs Console at https://code.google.com/apis/console and log in with your Google Account.
Click the Services link from the left-hand menu.
Activate the Google Maps JavaScript API v3 service.
Click the API Access link from the left-hand menu. Your API key is available from the API Access page, in the Simple API Access section. Maps API applications use the Key for browser apps.
here
Markup Code as follow:-
// Adds a marker with popup window information
var marker1Latlng = new google.maps.LatLng(35.65654,-106);
var contentString1 = 'I love New Mexico! More about the Land of Enchantment';
var infowindow = new google.maps.InfoWindow({
content: contentString1
});
var marker1 = new google.maps.Marker({
position: marker1Latlng,
map: map,
title: 'New Mexico'
});
google.maps.event.addListener(marker1, 'click', function() {
infowindow.open(map,marker1);
});
//End of Add Marker code
Hi Kanika in Fiddle it seems like the API key you are using is not a valid key. You might need to regenerate the API key for Google Maps API Engine from your Google Console.
Change this code lines - basically you don't need a api key in here
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyATC35pv00Ga3hRxP4t5W7NtM9as48PGVQs">
</script>
Replace with
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?v=3.exp">
</script>