So I have this example geolocation app in HTML5 and Javascript that is supposed to display the user's current location on google maps. For some reason, I cannot get this to work, even though all of my privacy settings are enabled. In my browser and my Cordova preview, the page is still blocked from tracking my location. I got the example code from https://mobiforge.com/design-development/html5-mobile-web-a-guide-geolocation-api where the example app works when I click on the link on the webpage. Any ideas why this isn't working? Here is the code:
<!DOCTYPE html>
<html>
<head>
<title>mobiForge geolocation map API demo</title>
<style>
body,html {height:100%}
#map {width:100%;height:100%;}
</style>
<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDbnJWPQoF5XQgI-akwQjyB6GKOFNtDO54"></script>
<script>
var map;
function initGeolocation() {
if (navigator && navigator.geolocation) {
var watchId = navigator.geolocation.watchPosition(successCallback,
errorCallback,
{enableHighAccuracy:true,timeout:60000,maximumAge:0});
} else {
console.log('Geolocation is not supported');
}
}
function errorCallback() {}
function successCallback(position) {
var myLatlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
if(map == undefined) {
var myOptions = {
zoom: 15,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map"), myOptions);
}
else map.panTo(myLatlng);
}
</script>
</head>
<body onload="javascript:initGeolocation()">
<div id="map">
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Security-Policy" content="script-src 'self' https://maps.googleapis.com/ https://maps.gstatic.com/ https://mts0.googleapis.com/ 'unsafe-inline' 'unsafe-eval'">
<script src="https://maps.googleapis.com/maps/api/js?key=Your_API_KEY&libraries=places" async defer></script>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script src="css/jquery-ui.css"></script>
<script src="js/jquery.min.js"></script>
<script src="js/jquery-ui.min.js"></script>
<script type="text/javascript">
var map;
var latitude;
var longitude;
var mapOptions;
var myLatLan;
document.addEventListener("deviceready", function() {
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}, false);
function onSuccess(position){
latitude=position.coords.latitude;
longitude=position.coords.longitude;
myLatLan={lat:latitude,lng:longitude};
console.log(myLatLan);
mapOptions={
zoom: 8,
center: myLatLan
};
}
function onError(error){
alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n');
}
function showmap(){
var div = document.getElementById("map_canvas");
map = new google.maps.Map(div,mapOptions);
myLatLng={lat:latitude,lng:longitude};
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hello World!'
});
}
</script>
</head>
<body>
<h3>GoogleMaps-Plugin</h3>
<div style="width:100%;height:400px" id="map_canvas"></div>
<button id="button" onclick="showmap()">Full Screen</button>
</body>
</html>
You have not mentioned url white listing , the meta tag as u can see above has that .
Hope this Helps.
Related
I'm trying to set up an Isoline on a map using the calculateisoline method of the HERE API but i keep getting following Error:
[timeout] http://route.nlp.nokia.com/routing/6.2/calculateisoline.json?xnlp=CL_JSMv3.0.15.0&app_id=KnNGic2KizTPB2mYGZy0&app_code=48Ound-jjgkPZXAHn2H1bw&mode=fastest%3Bcar&start=geo!52.5%2C13.4&time=PT0H15M request failed
The Code I'm using, which by the way is the original example from the documentation:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="viewport" content="initial-scale=1.0, width=device-width" />
<link rel="stylesheet" type="text/css"
href="https://js.cit.api.here.com/v3/3.0/mapsjs-ui.css" />
<script type="text/javascript"
src="https://js.cit.api.here.com/v3/3.0/mapsjs-core.js"></script>
<script type="text/javascript"
src="https://js.cit.api.here.com/v3/3.0/mapsjs-service.js"></script>
<script type="text/javascript"
src="https://js.cit.api.here.com/v3/3.0/mapsjs-ui.js"></script>
<script type="text/javascript"
src="https://js.cit.api.here.com/v3/3.0/mapsjs-mapevents.js"></script>
</head>
<body>
<div style="width: 800px; height: 600px" id="mapContainer" align="center"></div>
<script>
// Instantiate a map and platform object:
var platform = new H.service.Platform({
'app_id': 'APPID',
'app_code': 'APPCODE'
});
// Retrieve the target element for the map:
var targetElement = document.getElementById('mapContainer');
// Get the default map types from the platform object:
var defaultLayers = platform.createDefaultLayers();
// Instantiate the map:
var map = new H.Map(
document.getElementById('mapContainer'),
defaultLayers.normal.map,
{
zoom: 10,
center: {lat: 52.5159, lng: 13.3777}
});
// Create the parameters for the routing request:
var routingParams = {
'mode': 'fastest;car',
'start': 'geo!52.5,13.4',
'time': 'PT0H15M'
};
// Define a callback function to process the isoline response.
var onResult = function (result) {
var center = new H.geo.Point(
result.Response.Center.Latitude,
result.Response.Center.Longitude),
isolineCoords = result.Response.isolines[0].value,
strip = new H.geo.Strip(),
isolinePolygon,
isolineCenter;
// Add the returned isoline coordinates to a strip:
isolineCoords.forEach(function (coords) {
strip.pushLatLngAlt.apply(strip, coords.split(','));
});
// Create a polygon and a marker representing the isoline:
isolinePolygon = new H.map.Polygon(strip);
isolineCenter = new H.map.Marker(center);
// Add the polygon and marker to the map:
map.addObjects([isolineCenter, isolinePolygon]);
// Center and zoom the map so that the whole isoline polygon is
// in the viewport:
map.setViewBounds(isolinePolygon.getBounds());
};
// Get an instance of the enterprise routing service:
var enterpriseRouter = platform.getEnterpriseRoutingService();
// Call the Enterprise Routing API to calculate an isoline:
enterpriseRouter.calculateIsoline(
routingParams,
onResult,
function (error) {
alert(error.message);
});
</script>
</body>
You are using an old URL. URL with nokia isn't supported anymore. https://developer.here.com/news/20160217#.WXjlKNOGOqR
You need either update js library or change URL, if it's possible.
I'm using google maps API to make a map that retrieves data from the database and shows the corresponding markers on the map. I did this by following these instructions: https://developers.google.com/maps/articles/phpsqlajax_v3
What I'm now trying to do is create a page (called add_marker.php) that has a draggable marker so that the user can then add the new marker to the database based on the coordinates. I want to be able to see the other markers when I'm on this page. I also include the map code in all the pages so I don't want it to change drastically just for this page, so my approach is the following: Make the draggable marker invisible in all the pages except for the add_marker page by setting the icon setting to an empty string " ". Now the problem is, I can't change the icon's image so I can see it in the particular page I want it visible. I've searched quite a bit here in stackoverflow and found some solution, but none of these worked.
The error that I get is: add_marker.php:9 Uncaught Reference Error: drag_marker is not defined
(Even though I've made the marker variable global)
The code is the following:
map_code.php (This is the page that I made with the help of the link and is almost identical to that code except for some variable names. It's included in the files that use the map)
Any help would be greatly appreciated
<!DOCTYPE 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>PHP/MySQL & Google Maps Example</title>
<script src="https://maps.googleapis.com/maps/api/js?key=MY_KEY"
type="text/javascript"></script>
<script type="text/javascript">
var drag_marker;
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(37.511769, 22.371699),
zoom: 13,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
downloadUrl("phpsqlajax_genxml.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var content = markers[i].getAttribute("content");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("latitude")),
parseFloat(markers[i].getAttribute("longitude")));
var content = markers[i].getAttribute("content");
var icon = 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png';
var marker = new google.maps.Marker({
map: map,
position: point,
icon: 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png'
});
bindInfoWindow(marker, map, infoWindow, content, name);
}
});
*var uluru = {lat: 37.52, lng: 22.37};
drag_marker = new google.maps.Marker({
icon: " ",
draggable: true,
position: uluru,
map: map
});*
}
function SelectElement(valueToSelect)
{
var element = document.getElementById("markerList");
element.value = valueToSelect;
}
function bindInfoWindow(marker, map, infoWindow, html, name) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
infoWindow.setContent("<p>" + name + "<br />" +
html + "<br />");
SelectElement(name);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
</script>
</head>
<body onload="load()">
<div id="map" style="width: 99.5%; height: 40%"></div>
</body>
</html>
add_marker.php:
<html>
<head>
<title>My website</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript">
drag_marker.setIcon("http://maps.google.com/mapfiles/ms/icons/red-dot.png");
</script>';
</head>
<body>
<div id="container">
<div id="header">
<h1><img src="logo.png" align="center" alt="logo" style="width:300px;height:60px;"><img src="gavlab.png" align="right" alt="logo" style="width:200px;height:55px;"></h1>
</div>
<div id="content">
<div id="nav">
<h3>Πλοήγηση</h3>
<ul id="menu">
<li>Homepage</li>
<li align="left">Map</li>
<li>Admin log-in</li>
<li>info</li>
<li>Contact</li>
</ul>
</div>
<div id="main">
<h6 align="center">Map</h6>
<?php include("map_code.php"); ?>
<div align="center" id="admin_menu">
<?php
error_reporting(E_ALL & ~E_NOTICE ^ E_DEPRECATED ^ E_WARNING );
//http://www.clker.com/cliparts/e/3/F/I/0/A/google-maps-marker-for-residencelamontagne-hi.png
// icon:"http://maps.google.com/mapfiles/ms/icons/red-dot.png",
SESSION_START();
if($_SESSION['username'] == "admin"||$_SESSION['username'] == "username"){
echo '<p align="center" style="color:#8A2908"> Welcome εδώ.</p>';
$con= mysql_connect('localhost','root','');
mysql_set_charset('utf8');
mysql_select_db('qr code');
mysql_query("SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'", $con);
$sql="SELECT * FROM array1";
$records=mysql_query($sql);
echo '<form id="main_form" name = "add_new_marker" action="marker_info.php" method="post">';
'</form>';
}
else echo '<p align="center" style="color:#8A2908">Please log in εδώ.</p>';
?>
</div>
</div>
</div>
<div id="footer">
Copyright © 2016 Name Here
</div>
</div>
</body>
</html>
You are attempting to use the drag_marker variable before it is defined (and probably also before it is initialized, look at the HTML/JavaScript rendered in the browser).
To deal with the timing issue, try:
google.maps.event.addDomListener(window, 'load', function() {
drag_marker.setIcon("http://maps.google.com/mapfiles/ms/icons/red-dot.png");
}):
After being reading some time... I wanted to start use the Google Maps API for Javascript. I got the key on their website, I tried many ways to create maps but now, I want to create a map by a previous "location" so first, I use the Geocoder.geocode() and then I create the map, last night it was working okey.
So, I decided to start use overlays (Markers) in these maps but I don't know I'm getting the Uncaught error: google is not defined.
I read a bit about it and i know most of times is about asynchronous problem but, I still don't know how fix it, here is the code:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
html, body { height: 100%; margin: 0; padding: 0; }
#map { height: 100%; }
</style>
</head>
<body>
<div id="map"></div>
<script src="https://code.jquery.com/jquery-2.2.3.min.js" integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo=" crossorigin="anonymous"></script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAeaWLxSHFEdwWEVVYajslt7R9eP0ZpLXQ&callback=initMap"></script>
<script type="text/javascript">
var sLocation = "Castillejos 265 Barcelona";
var sLocationToSearch =sLocation.split(' ').join('+');
$.ajax({
type: 'GET',
url: 'https://maps.googleapis.com/maps/api/geocode/json?address='+ sLocationToSearch +'&key=AIzaSyAeaWLxSHFEdwWEVVYajslt7R9eP0ZpLXQ',
success: function(res){
// ParseFloat the <latitud> and <longitud>
//var myLatlng = new google.maps.LatLng(parseFloat(trader.geo.lat),parseFloat(trader.geo.lon));
initMap(res.results[0].geometry.location);
},
error: function(error){
console.log(error);
}
});
function initMap(oLatlng){
var map = new google.maps.Map(document.getElementById('map'), {
center: oLatlng,
zoom: 15
});
}
</script>
</body>
</html>
thanks a lot for your help
call javascript after page is loaded by using window.onload
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
html, body
{
height: 100%;
margin: 0;
padding: 0;
}
#map
{
height: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<script src="https://code.jquery.com/jquery-2.2.3.min.js" integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo=" crossorigin="anonymous"></script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAeaWLxSHFEdwWEVVYajslt7R9eP0ZpLXQ&callback=initMap"></script>
<script type="text/javascript">
window.onload = function()
{
var sLocation = "Castillejos 265 Barcelona";
var sLocationToSearch = sLocation.split(' ').join('+');
$.ajax({
type : 'GET',
url : 'https://maps.googleapis.com/maps/api/geocode/json?address=' + sLocationToSearch + '&key=AIzaSyAeaWLxSHFEdwWEVVYajslt7R9eP0ZpLXQ',
success : function(res)
{
// ParseFloat the <latitud> and <longitud>
//var myLatlng = new google.maps.LatLng(parseFloat(trader.geo.lat),parseFloat(trader.geo.lon));
initMap(res.results[0].geometry.location);
},
error : function(error)
{
console.log(error);
}
});
function initMap(oLatlng)
{
var map = new google.maps.Map(document.getElementById('map'), {
center : oLatlng,
zoom : 15
});
}
}
</script>
</body>
</html>
I am trying to make a google map api with markers, which will show the latitude and longitude of some places.I am trying to do this with json file but it is not working..
here is my code ..
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Cluster Map</title>
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/src/markerclusterer.js" type="text/javascript"></script>
<script type="text/javascript">
var map;
var markers = [];
function initialize() {
geocoder = new google.maps.Geocoder();
var center = new google.maps.LatLng(43.474144,-112.03866);
map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
markMultiple();
}
function markMap(latLng, content){
var marker = new google.maps.Marker({
position: latLng
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(content);
infowindow.open(map, marker);
});
markers.push(marker);
}
function markMultiple(){
$.parseJSON('test.json', function(data) {
$.each(data.markers, function(i, obj) {
var latLng = new google.maps.LatLng(obj.lat,obj.lng);
var content = obj.id + ':' + obj.lat + ',' + obj.lng;
markMap(latLng, content);
});
});
var markerCluster = new MarkerClusterer(map, markers);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-container">
<div id="map"></div>
</div>
</body>
please help me..
Engineer was right, you need to use $.getJSON method, $.parseJSON takes a JSON string, it doesn't load an external file.
getJSON: http://api.jquery.com/jQuery.getJSON/
parseJSON: http://api.jquery.com/jQuery.parseJSON/
I put your code in a jsFiddle and it is working with getJSON and an alternative test JSON file (you didn't provide the original test.json you're using).
$.getJSON('test.json', function(data) {
$.each(data.markers, function(i, obj) {
var latLng = new google.maps.LatLng(obj.lat,obj.lng);
var content = obj.id + ':' + obj.lat + ',' + obj.lng;
markMap(latLng, content);
});
});
http://jsfiddle.net/WYfjv/
If your code is not working maybe your JSON is not well formatted (try JSONLINT to test it). Also, if you are already improving, I would advise to use a normal for loop rather than $.each :)
i've been dealing with this couple of hours and i still cant figure how to do it.
my objective is to display only one marker when searching addresses close to each other.
below you have the code i use in my html in order to search for addresses, note - i'm developing a windows application that does such, in which case you might find some missing stuff to do actions by clicking buttons since this is done via .NET windows application
html code
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script type="text/javascript" src="http://maps.google.com.mx/maps/api/js?sensor=true&language=es"></script>
<script type="text/javascript">
var G = google.maps;
var map;
var geocoder = new G.Geocoder();
var marker;
var markersArray = [1];
function initialize() {
createMap();
geocode('Chicago');
}
function createMap() {
var myOptions = {
center: new G.LatLng(0,0),
zoom: 17,
mapTypeId: G.MapTypeId.ROADMAP
}
map = new G.Map(document.getElementById("map_canvas"), myOptions);
}
function geocode(address){
geocoder.geocode({ 'address': (address ? address : "Miami Beach, Florida")}, function (results, status) {
if (status == G.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
marker = new G.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
reading previous posts i know that if/else statement has to be used but cant get it right.
your help is very appreciated.
Leo P.
You can add a small bit of code to the beginning of your Geocode function that will remove the previous marker before setting a new one. Try this:
function geocode(address){
if (marker) {
marker.setMap(null);
}
geocoder.geocode({ 'address': (address ? address : "Miami Beach, Florida")}, function (results, status) {
Create only one marker as a global variable and change its position as needed. Like that you also save memory because you're not creating a new marker object on each request:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style>
html, body {width:100%; height:100%}
</style>
<script type="text/javascript" src="http://maps.google.com.mx/maps/api/js?sensor=true&language=es"></script>
<script type="text/javascript">
var G = google.maps;
var map;
var marker;
var geocoder = new G.Geocoder();
function initialize() {
createMap();
geocode('Chicago');
}
function createMap() {
var myOptions = {
center: new G.LatLng(0,0),
zoom: 17,
mapTypeId: G.MapTypeId.ROADMAP
}
map = new G.Map(document.getElementById("map_canvas"), myOptions);
// Create a single marker, (global variable), and don't give it a position just yet.
marker = new G.Marker({
map: map,
animation: google.maps.Animation.DROP,
});
}
function geocode(address){
geocoder.geocode({ 'address': (address ? address : "Miami Beach, Florida")}, function (results, status) {
if (status == G.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
//Position the marker
marker.setPosition(results[0].geometry.location);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>