Trying to create google map using javascript in angular - javascript

I am trying to create the google map with PubNub and angular, but the map is not displaying if I use the angular framework, but If I use directly javascript and HTML it is working.
can any one tell me wat I am doing wrong.
HTML: app.component.html
<!doctype html>
<html>
<head>
<title>Google Maps Example</title>
<script src="https://cdn.pubnub.com/sdk/javascript/pubnub.4.19.0.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" />
</head>
<body>
<div class="container">
<h1>PubNub Google Maps Tutorial - Live Device Location</h1>
<div id="map-canvas" style="width:600px;height:400px"></div>
</div>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&key=APIKEY&callback=initialize"></script>
<script src="../app/app.js"></script>
</body>
After this I have created Javascript file, Instead of using Typescript.
app.js:
window.lat = 37.7850;
window.lng = -122.4383;
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(updatePosition);
}
return null;
};
function updatePosition(position) {
if (position) {
window.lat = position.coords.latitude;
window.lng = position.coords.longitude;
}
}
setInterval(function(){updatePosition(getLocation());}, 10000);
function currentLocation() {
return {lat:window.lat, lng:window.lng};
};
var map;
var mark;
var initialize = function() {
map = new google.maps.Map(document.getElementById('map-canvas'), {center:{lat:lat,lng:lng},zoom:12});
mark = new google.maps.Marker({position:{lat:lat, lng:lng}, map:map});
};
window.initialize = initialize;
var redraw = function(payload) {
lat = payload.message.lat;
lng = payload.message.lng;
map.setCenter({lat:lat, lng:lng, alt:0});
mark.setPosition({lat:lat, lng:lng, alt:0});
};
var pnChannel = "map2-channel";
var pubnub = new PubNub({
publishKey: 'YOUR_PUB_KEY',
subscribeKey: 'YOUR_SUB_KEY'
});
pubnub.subscribe({channels: [pnChannel]});
pubnub.addListener({message:redraw});
setInterval(function() {
pubnub.publish({channel:pnChannel, message:currentLocation()});
}, 5000);
can anyone help me with how to solve this problem..

This could be related to the stage of the component's life-cycle where you execute your typescript code. Your code needs to be executed after the template has been rendered, because it expects the elements to exist: document.getElementById('map-canvas')
You can try executing the code in the ngAfterViewInit method of your component

Related

How Can I work with Leaflet Control Geocode?

I plan to add a leaflet control geocoder or a search box to my app.
Although I wrote the needed code it doesn't display any geocoder and
I don't know what is wrong. I have provided a part of my index.html
file including related code.
<link rel="stylesheet" href="{% static 'geocoder/Control.Geocoder.css' %}" />
<script type="text/javascript" src="{% static 'geocoder/Control.Geocoder.js' %}"></script>
<script>
var geocoder = L.Control.geocoder().on('markgeocode', function(event) {
var center = event.geocode.center;
L.marker(center).addTo(map);
map.setView(center, map.getZoom());
}).addTo(map);
</script>
You have to set the geocode "type": Types
var _geocoderType = L.Control.Geocoder.nominatim();
var geocoder = L.Control.geocoder({
geocoder: _geocoderType
}).addTo(map);
geocoder.on('markgeocode', function(event) {
var center = event.geocode.center;
L.marker(center).addTo(map);
map.setView(center, map.getZoom());
});

loading google maps in windows phone 8.1 using webview

I have created a sample app to load google maps in windows phone 8.1. Using the webview approch I'm not able to launch google maps, please help me in fixing this.. Below is the code:
default.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Maps</title>
<!-- WinJS references -->
<!-- At runtime, ui-themed.css resolves to ui-themed.theme-light.css or ui-themed.theme-dark.css
based on the user’s theme setting. This is part of the MRT resource loading functionality. -->
<link href="/css/ui-themed.css" rel="stylesheet" />
<script src="//Microsoft.Phone.WinJS.2.1/js/base.js"></script>
<script src="//Microsoft.Phone.WinJS.2.1/js/ui.js"></script>
<!-- Maps references -->
<link href="/css/default.css" rel="stylesheet" />
<script src="/js/default.js"></script>
</head>
<body>
<h1>Google Maps API on Windows phone 8.1</h1>
<x-ms-webview id="Map" src="ms-appx-web:///map.html" style="width:500px;height:500px;"></x-ms-webview>
</body>
</html>
maps.html:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="//Microsoft.Phone.WinJS.2.1/js/base.js"></script>
<script src="//Microsoft.Phone.WinJS.2.1/js/ui.js"></script>
<!-- map references -->
<link href="/map.css" rel="stylesheet" />
<script src="http://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize"></script>
<script src="/map.js"></script>
</head>
<body>
<div id="mapdisplay" height="500px" width="500px"></div>
</body>
</html>
maps.js:
var map;
var dataResults;
function initialize() {
map = new google.maps.Map(document.getElementById('mapdisplay'), {
zoom: 3,
center: new google.maps.LatLng(40, -187.3),
mapTypeId: google.maps.MapTypeId.TERRAIN
});
addMarkers();
}
eqfeed_callback = function (results) {
dataResults = results;
}
function addMarkers() {
for (var i = 0; i < dataResults.features.length; i++) {
var quake = dataResults.features[i];
var coors = quake.geometry.coordinates;
var latLong = new google.maps.LatLng(coors[1], coors[0]);
var marker = new google.maps.Marker({
position: latLong,
map: map
//icon: getCircle(earthquake.properties.mag)
});
}
}
function getCircle(magnitude) {
return {
path: google.maps.SymbolPath.CIRCLE,
fillColor: 'red',
fillOpacity: .2,
scale: Math.pow(2, magnitude) / Math.PI,
strokeColor: 'white',
strokeWeight: .5
};
}
What's the mistake I'm doing in the above code, please let me know..
"maps.html" does not work because of multiple synchronicity issues.
Load maps.js beforehttp://maps.googleapis.com/maps/api/js so initialise is defined,
Load http://maps.googleapis.com/maps/api/jsand after the HTML has been parsed so the mapdisplay element exists when initialise is called.
Call addMarkers from eqfeed_callback not initialise so dataResults has been set with valid object data.
Most of this could have been found out by opening the developers console and checking it for errors when viewing "maps.html" in a desktop browser. You may also like to research other questions on the topic and/or check the api documentation for working examples - and notice how the api documentation uses defer and async attributes on the script tag to make sure it doesn't execute until after the page has been parsed.

Here Maps API - Basic place display (placeId)

I implemented the map on web page using JavaScript API, and now I want to show the basic information about some location. In JavaScript API documentation, I found a part of which is called "Basic place display" in Places Components section, but there is an example of how to render information using placeId.
I need to be able to retrieve information using location coordinates if it is possible. I tried to display information using PHP code that define coordinates for some location on the map instead of using placeId, but it's not working.
This is an example of code that I used:
var basicPlace = new nokia.places.widgets.Place({
placeId: PHP code instead of placeId.
*exp: [<?php code;?>, <?php echo code;?>],*
targetNode: "map",
template: "nokia.blue.place"
});
Is it possible to solve the problem like that, or there is a method that does not involve placeId.
Links: Here Developer, Here JavaScript API
If you read the nokia.places.widgets.Place documentation, you will see that placeId is a mandatory parameter. It is in effect the primary key for the place information that is held by HERE. You will therefore need to make another request using the JavaScript API prior to display in order to obtain the placeId so you can show your place details. The obvious thing to do here is to make a category request first, and store the placeId with each marker as shown below:
// Function for receiving search results from places search and process them
var processResults = function (data, requestStatus, requestId) {
var i, len, locations, marker;
if (requestStatus == "OK") {
locations = data.results ? data.results.items : [data.location];
if (locations.length > 0) {
for (i = 0, len = locations.length; i < len; i++) {
// Add a marker and store the placeId
marker = new nokia.maps.map.StandardMarker(locations[i].position,
{ text: i+1 ,
placeId : locations[i].placeId});
resultSet.objects.add(marker);
}
}
});
// etc.. etc...
The second part is to add the click listener which displays an infobubble and populates the Place Widget using the stored placeId:
resultSet.addListener("click" , function(evt) {
infoBubbles.openBubble("<div id='basicPlaceContainer'></div>",
evt.target.coordinate);
var basicPlace = new nokia.places.widgets.Place({
placeId: evt.target.placeId,
targetNode: "basicPlaceContainer",
template: "nokia.blue.bubble"
});
}, false);
The complete working example can be seen below:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=7; IE=EmulateIE9; IE=10" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Nokia Maps API for JavaScript Example: Search by category</title>
<meta name="description" content="Search by category"/>
<script type="text/javascript" charset="UTF-8" src="http://js.cit.api.here.com/se/2.5.3/jsl.js?with=all"></script>
</head>
<body>
<div id="mapContainer" style="width:540px; height:334px;"></div>
<script type="text/javascript" id="exampleJsSource">
/* Setup authentication app_id and app_code
*/
nokia.Settings.set("app_id", "YOUR APP ID");
nokia.Settings.set("app_code", "YOUR APP CODE");
// Use staging environment (remove the line for production environment)
nokia.Settings.set("serviceMode", "cit");
// Get the DOM node to which we will append the map
var mapContainer = document.getElementById("mapContainer");
// Create a map inside the map container DOM node
var map = new nokia.maps.map.Display(mapContainer, {
// Initial center and zoom level of the map
center: [52.51, 13.4],
zoomLevel: 10,
components: [
new nokia.maps.map.component.Behavior()
]
});
this.infoBubbles = new nokia.maps.map.component.InfoBubbles();
map.components.add(infoBubbles);
var searchCenter = new nokia.maps.geo.Coordinate(52.51, 13.4),
searchManager = nokia.places.search.manager,
resultSet;
// Function for receiving search results from places search and process them
var processResults = function (data, requestStatus, requestId) {
var i, len, locations, marker;
if (requestStatus == "OK") {
locations = data.results ? data.results.items : [data.location];
if (locations.length > 0) {
if (resultSet) map.objects.remove(resultSet);
resultSet = new nokia.maps.map.Container();
resultSet.addListener("click" , function(evt) {
infoBubbles.openBubble("<div id='basicPlaceContainer'></div>", evt.target.coordinate);
var basicPlace = new nokia.places.widgets.Place({
placeId: evt.target.placeId,
targetNode: "basicPlaceContainer",
template: "nokia.blue.bubble"
});
}, false);
for (i = 0, len = locations.length; i < len; i++) {
marker = new nokia.maps.map.StandardMarker(locations[i].position,
{ text: i+1 ,
placeId : locations[i].placeId});
resultSet.objects.add(marker);
}
map.objects.add(resultSet);
map.zoomTo(resultSet.getBoundingBox(), false);
} else {
alert("Your search produced no results!");
}
} else {
alert("The search request failed");
}
};
// Make a place search request
var category = "eat-drink";
map.addListener("displayready", function () {
searchManager.findPlacesByCategory({
category: category,
onComplete: processResults,
searchCenter: searchCenter
});
});
</script>
</body>
</html>
The result can be see below:

How do I add Google Maps on my site?

I have a form and I want to add a "select location" option.
How can I do this, and how can I place a pin as the selected location?
You may want to consider using the Google Maps API, as davek already suggested.
The following example may help you getting started. All you would need to do is to change the JavaScript variable userLocation with the location chosen by your users from the drop-down field you mention.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps API Demo</title>
<script src="http://maps.google.com/maps?file=api&v=2&sensor=false"
type="text/javascript"></script>
</head>
<body onunload="GUnload()">
<div id="map_canvas" style="width: 400px; height: 300px"></div>
<script type="text/javascript">
var userLocation = 'London, UK';
if (GBrowserIsCompatible()) {
var geocoder = new GClientGeocoder();
geocoder.getLocations(userLocation, function (locations) {
if (locations.Placemark)
{
var north = locations.Placemark[0].ExtendedData.LatLonBox.north;
var south = locations.Placemark[0].ExtendedData.LatLonBox.south;
var east = locations.Placemark[0].ExtendedData.LatLonBox.east;
var west = locations.Placemark[0].ExtendedData.LatLonBox.west;
var bounds = new GLatLngBounds(new GLatLng(south, west),
new GLatLng(north, east));
var map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
map.addOverlay(new GMarker(bounds.getCenter()));
}
});
}
</script>
</body>
</html>
The above example would render a map like the one below:
The map will not show if the Google Client-side Geocoder cannot retreive the coordinates from the address.
Check out the Google Maps API. There's lots of information there and several examples:without knowing more about your environment/requirements it is difficult to be more specific.

Javascript can't call an object inside a function

Sorry, I am new to javascript. I am trying to call an object from inside a function to allow me to get a variable from a flash file at set intervals. For some reason the object is not working inside the timer function.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>DIY Map</title>
<style>
* { margin:0; padding:0; }
</style>
</head>
<body style="font-family:verdana;color:#999; background-image:url('bg.png'); background-repeat:no-repeat;">
<script type="text/javascript" src="js/JavaScriptFlashGateway.js"></script>
<script type="text/javascript" src="js/Exception.js"></script>
<script type="text/javascript" src="js/FlashTag.js"></script>
<script type="text/javascript" src="js/FlashSerializer.js"></script>
<script type="text/javascript" src="js/FlashProxy.js"></script>
<script type="text/javascript">
var uid = new Date().getTime();
var flashProxy = new FlashProxy(uid, 'js/JavaScriptFlashGateway.swf');
var tag = new FlashTag('world.swf?data_file=data.xml, 600, 325);
tag.setFlashvars('lcId='+uid);
tag.write(document);
</script>
//flashProxy.call works here:
<p>Zoom Out
Get new data
<p>getZoom | getCoords</p>
<script type="text/javascript">
// Start the refreshing process
var seconds = 3;
var zoom;
var coords;
//timer loop
function checkmap()
{
//flashProxy doesn't work here
flashProxy.call('getCoords');
flashProxy.call('getZoom');
alert (coords);
alert (zoom);
setTimeout('checkmap()',seconds * 1000);
}
checkmap();
//Returns results here:
function gotCoords(n)
{
coords = n;
}
function gotZoom(n)
{
zoom = n;
}
</script>
To clarify, I am trying to get the flashProxy.call('****') to work in the checkmap() function. Thanks in advance.
I found the problem... it was that because there was no timer to start the inital flashproxy.call it was executing before the flash was loaded. I just replaced
checkmap();
with another
setTimeout('checkmap()',seconds * 1000);
Thanks everyone anyway
Did you know you have an extra/unclosed script tag in your source? This would cause problems.
<script type="text/javascript"> // This is your opening tag
<script type="text/javascript"> // Oops, this is parsed by the script engine
var uid = new Date().getTime();
var flashProxy = new FlashProxy(uid, 'js/JavaScriptFlashGateway.swf');
var tag = new FlashTag('world.swf?data_file=data.xml, 600, 325);
tag.setFlashvars('lcId='+uid);
tag.write(document);
</script>
The above code would throw a syntax error in any javascript engine and halt further execution.
Your source is also missing a ' on the following line:
var tag = new FlashTag('world.swf?data_file=data.xml, 600, 325);

Categories

Resources