My code:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script type="text/javascript" src="jquery.ui.map.full.min.js"></script>
<script>
function initialize() {
$('#map_canvas').gmap().bind('init', function() {
// This URL won't work on your localhost, so you need to change it
// see http://en.wikipedia.org/wiki/Same_origin_policy
$.getJSON( 'demo.json', function(data) {
$.each( data.markers, function(i, marker) {
$('#map_canvas').gmap('addMarker', {
'position': new google.maps.getLatLng(marker.town),
'bounds': true
}).click(function() {
$('#map_canvas').gmap('openInfoWindow', { 'content': marker.content }, this);
});
});
});
});
}
</script>
Why does the google.maps.getLatLng not work?
UPDATE:
$('#map_canvas').gmap('addMarker', { geocoder = new google.maps.Geocoder(); 'position': new google.maps.LatLng(geocoder.getLatLng(marker.town)), 'bounds': true })
How do I find the latutide and longitude based on a town name? I have just tried the above without result.
Why does the google.maps.getLatLng not work?
Where do you find that in the documentation?
The correct syntax for the google.maps.LatLng constructor is:
new google.maps.LatLng(<latitude>, <longitude>)
where <latitude> and <longitude> are numbers
To get the geographic coordinates of a postal address, you need to use a geocoder.
Related
I'm trying to implement a map with a route that has a waypoint and a dynamic origin within a Google Site. I'd like to set the origin based on the user's location who access the Google Sites and I'm using the HTML5 Geolocation API to retrieve the user's geolocation. However, I'm not able to retrieve properly the user's geolocation.
Here you will find the code I'm currently implementing.
<!DOCTYPE html>
<html>
<head>
<title>PATH A</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<style type="text/css">
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
<script>
function initMap() {
const directionsService = new google.maps.DirectionsService();
const directionsRenderer = new google.maps.DirectionsRenderer();
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 8,
center: { lat: 37.132, lng: 13.869 },
});
directionsRenderer.setMap(map);
const onChangeHandler = function () {
calculateAndDisplayRoute(directionsService, directionsRenderer);
};
window.onload = onChangeHandler;
}
function setPosition(position){
currentOrigin = {};
currentOrigin.lat = position.coords.latitude;
currentOrigin.lng = position.coord.longitude;
}
function calculateAndDisplayRoute(directionsService, directionsRenderer){
let currentOrigin = new google.maps.LatLng(37.081, 14.214);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(setPosition);
} else {
// Browser doesn't support Geolocation
console.log("Browser does not support geolocation");
}
const waypts = [];
waypts.push({
location: { lat: 37.261, lng: 13.588},
stopover: true
});
directionsService.route({
origin: currentOrigin,
destination: {
lat: 37.314 , lng: 13.576
},
optimizeWaypoints: false,
waypoints: waypts,
travelMode: google.maps.TravelMode.DRIVING
}, (response, status) => {
if(status === "OK" && response) {
directionsRenderer.setDirections(response);
} else {
console.log("An error occurred: " + status);
}
});
}
</script>
</head>
<body>
<div id="map"></div>
<!-- Async script executes immediately and must be after any DOM elements used in callback. -->
<script
src="https://maps.googleapis.com/maps/api/js?key=*********&callback=initMap&libraries=&v=weekly"
async
></script>
</body>
</html>
Is the Geolocation API somehow blocked by the Google Sites' policies? If so, is there any other way to set up a dynamic origin? The desired solution is to have a map on the site that has a route with a specific waypoint.
Thanks in advance for your attention.
So a couple of things first I think you have a typo in your setPosition callback function the longitude should be position.coords.longitude . Also you need to set the center of the google maps object when the navigator returns a lat and lng. Right now currentOrigin is out of scope of the map and never is able to update. One thing you could possibly try is passing a reference of your map object to calculateAndDisplayRoute and setting the map's location in the setPosition callback.
Try this:
function initMap() {
const directionsService = new google.maps.DirectionsService();
const directionsRenderer = new google.maps.DirectionsRenderer();
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 8,
center: { lat: 37.132, lng: 13.869 },
});
directionsRenderer.setMap(map);
const onChangeHandler = function () {
calculateAndDisplayRoute(directionsService, directionsRenderer, map);
};
window.onload = onChangeHandler;
}
function setPosition(position, map){
currentOrigin = {};
map.setCenter({ lat : position.coords.latitude, lng: position.coords.longitude });
}
function calculateAndDisplayRoute(directionsService, directionsRenderer, map){
let currentOrigin = new google.maps.LatLng(37.081, 14.214);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
setPosition(position, map);
});
} else {
// Browser doesn't support Geolocation
console.log("Browser does not support geolocation");
}
const waypts = [];
waypts.push({
location: { lat: 37.261, lng: 13.588},
stopover: true
});
directionsService.route({
origin: currentOrigin,
destination: {
lat: 37.314 , lng: 13.576
},
optimizeWaypoints: false,
waypoints: waypts,
travelMode: google.maps.TravelMode.DRIVING
}, (response, status) => {
if(status === "OK" && response) {
directionsRenderer.setDirections(response);
} else {
console.log("An error occurred: " + status);
}
});
}
I passed the map object through to the callback so that setCenter could be called on the navigators position.
I'm trying to setup a Web Page using the same data that is being pulled for the first chart. Data is being pulled by an edmx entity model. The code below works for single graph. I want to add a Pie Chart on the same page as well using the same data. All the examples I've seen are for graphs using static data. My code is below, I know I would need to just reproduce what I have in some fashion. Thanks,
<script type="text/javascript" src="https://www.google.com/jsapi">
</script>
#section Scripts{
<script>
$(document).ready(function () {
//Load Data Here
var chartData = null;
$.ajax({
url: '/GoogleChart/GetSalesData',
type: 'GET',
dataType: 'json',
data: '',
success: function (d) {
chartData = d;
},
error: function () {
alert('Error!');
}
}).done(function () {
drawChart(chartData);
});
});
function drawChart(d) {
var chartData = d;
var data = null;
data = google.visualization.arrayToDataTable(chartData);
var view = new google.visualization.DataView(data);
view.setColumns([0, {
type: 'number',
label: data.getColumnLabel(0),
calc: function () { return 0; }
}, {
type: 'number',
label: data.getColumnLabel(1),
calc: function () { return 0; }
}, {
type: 'number',
label: data.getColumnLabel(2),
calc: function () { return 0; }
}]);
var chart = new google.visualization.ColumnChart(document.getElementById('visualization1'));
var options = {
}
var runFirstTime = google.visualization.events.addListener(chart, 'ready', function () {
google.visualization.events.removeListener(runFirstTime);
chart.draw(data, options);
});
chart.draw(view, options);
}
google.load('visualization', '1', { packages: ['corechart'] });
</script>
<div id="visualization1" style="width:900px; height:500px"></div>
}
first, recommend using...
<script src="https://www.gstatic.com/charts/loader.js"></script>
not...
<script src="https://www.google.com/jsapi"></script>
according to the release notes...
The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. Please use the new gstatic loader.js from now on.
note: the load statement will be the only difference, as seen below...
next, you can draw as many charts as necessary,
after the load statement has completed
you must set a callback to know for sure,
that google charts has loaded all of the requested packages...
multiple packages can be loaded at the same time
google.charts.load('current', {
callback: loadData,
packages: ['corechart', 'table']
});
the callback will also wait for the document to finish loading...
as such, $(document).ready isn't needed
recommend setup similar to following...
<script src="https://www.gstatic.com/charts/loader.js"></script>
#section Scripts{
<script>
function loadData() {
$.ajax({
url: '/GoogleChart/GetSalesData',
type: 'GET',
dataType: 'json',
data: '',
}).fail(function (jq, text, errMsg) {
console.log(text + ': ' + errMsg);
}).done(function (jsonData) {
drawCharts(jsonData);
});
}
function drawCharts(jsonData) {
var chartData = google.visualization.arrayToDataTable(jsonData);
var chartCol = new google.visualization.ColumnChart(document.getElementById('visualization-col'));
chartCol.draw(chartData);
var chartPie = new google.visualization.PieChart(document.getElementById('visualization-pie'));
chartPie.draw(chartData);
var chartTable = new google.visualization.Table(document.getElementById('visualization-table'));
chartTable.draw(chartData);
}
google.charts.load('current', {
callback: loadData,
packages: ['corechart', 'table']
});
</script>
<div id="visualization-col"></div>
<div id="visualization-pie"></div>
<div id="visualization-table"></div>
}
note: each chart has a specific data format
although most of the charts in 'corechart' will be fine,
not all charts may work with the same data table...
I'm trying to learn jVectormap and I'm stuck trying to return the country when clicked on. Is there any way to convert the code into a country, or just get the country when clicking on the map?
<script>
$(function () {
$('#world-map').vectorMap ({
onRegionClick: function (e, code) {
console.log (code);
}
});
});
</script>
Here ya go
onRegionClick: function (event, code) {
var map = $('#world-map').vectorMap('get', 'mapObject');
var name = map.getRegionName(code);
},
Use this
onRegionClick:function(event, code){
var name = (code);
window.location.href("http://your url address"+ code);
}
change the "your url adress" to your link address.
All script
<script>
$(function(){
$('#world-map').vectorMap({
onRegionClick:function(event, code){
var name = (code);
window.location.href("http://your url address"+ code);
}
});
});
</script>
Look, I'm using Google Maps JavaScript API v3. The user fills in an address and I show the streetview of that address. Everything's fine (a lot of locations work perfectly), till a enter a location like "Laken". It just displays grey, nothing else. I want to prevent the user from continuing to the next page with a grey image instead of a google maps streetview.
When I fill in Laken, the getPanoramaByLocation() function returns status == "OK", because it has found something, but its not a visible image, it's just grey. How can I prevent the API from doing this? Something like, when you can't display this location(is grey), display the next available location nearby.
Here's an extract from the code:
Function:
<script type="text/javascript">
//this is a standard location that I show when te user starts
var map;
var huis_lat,huis_lng;
$(document).ready(function(){
map = new GMaps({
el: '#map',
lat: -12.043333,
lng: -77.028333
});
//SAVE HOMELAT&LONGT
$('#geocoding_form').submit(function(e){
var address=document.getElementById("address").value;
e.preventDefault();
GMaps.geocode({
address: $('#address').val().trim(),
callback: function(results, status)
{
if(status=='OK'){
var latlng = results[0].geometry.location;
huis_lat=latlng.lat();
huis_lng=latlng.lng();
verander(huis_lat, huis_lng);
document.getElementById("div_overlayStart").style.display="none";
document.getElementById("div_overlayThuis").style.display="block";
}
else if(!address) //no address
{
alert("fout?")
document.getElementById('alarm1').innerHTML = 'FILL IN ADDRESS';
}
else if(status=='UNKNOWN_ERROR')
{
document.getElementById('alarm1').innerHTML = 'UNKNOWN ERROR!';
}
else if(status=='ZERO_RESULTS')
{
document.getElementById('alarm1').innerHTML = 'UNKNOWN ADDRESS!';
}
}
});
});
});
</script>
HTML:
EX: Fill in: Kongingslaan 1, Laken
<body>
<form method="post" id="geocoding_form">
<div class="input">
<input type="text" id="address" name="address" />
<button type="submit" class="linksSocial" style="border: 0; background: transparent">
<img src="images/btn_job.png" width="231" heght="36" alt="submit" />
</button>
</div>
</form>
</body>
Function verander():
<script type="text/javascript">
function verander(google_lat, google_lng) {
var bryantPark = new google.maps.LatLng(google_lat, google_lng);
var panoramaOptions = {
position:bryantPark,
pov: {
heading: 185,
pitch:0,
zoom:1,
},
panControl : false,
streetViewControl : false,
mapTypeControl: false,
overviewMapControl: false ,
linksControl: false,
addressControl:false,
zoomControl : false,
}
map = new google.maps.StreetViewPanorama(document.getElementById("map_canvas"), panoramaOptions);
map.setVisible(true);
}
</script>
Use google.maps.StreetViewService.getPanoramaByLocation() to determine if there is a panorama available for the given location.
Quick and dirty solution. I noticed resizing the Window worked for me on this problem. And it also worked if you fire the event via js.
window.dispatchEvent(new Event('resize'));
Try this :
$(document).ready(function(){
var map = new GMaps({
el: '#map',
lat: -12.043333,
lng: -77.028333
});
//SAVE HOMELAT&LONGT
$('#geocoding_form').submit(function(e) {
e.preventDefault();
var address = $('#address').val().trim();
if(!address.length) {
$('#alarm1').html('Fill in your address!');
}
GMaps.geocode({
address: address,
callback: function(results, status) {
if(status !== 'OK' || results.length == 0) {
$("#div_overlayStart").show();
$("#div_overlayThuis").hide();
}
if(status !== 'OK') {
$('#alarm1').text('Something went wrong!');
}
else if(results.length == 0) {
$('#alarm1').html('No results found!');
}
else {
$('#alarm1').text('');
var latlng = results[0].geometry.location;
verander(latlng.lat(), latlng.lng());
$("#div_overlayStart").hide();
$("#div_overlayThuis").show();
}
}
});
});
});
I also had problems with StreetView displaying 'grey' at some locations.
I don't like the solution given here.
Have a look at my solution in another post, which is also to do with StreetView being displayed 'grey' at some locations -->
Google maps streetview tiles do not load in Firefox initially, only after dragging
This solves the problem:
<script type="text/javascript">
var map;
var huis_lat,huis_lng;
var richting = 0;
$(document).ready(function(){
map = new GMaps({
el: '#map',
lat: -12.043333,
lng: -77.028333
});
//SAVE HOMELONG/LAT IN VAR
$('#geocoding_form').submit(function(e){
var address=document.getElementById("address").value;
/* STATUS
OK The request was successful.
UNKNOWN_ERROR The request could not be successfully processed, yet the exact reason for failure is unknown.
ZERO_RESULTS There are no nearby panoramas.
*/
//CHECK IF ADDRESS IS VALID (IS THEIR A VALID X/Y COORDINATE FOR IT?)
e.preventDefault();
GMaps.geocode({
address: $('#address').val().trim(),
callback: function(results, status)
{
if(status=='OK'){
var latlng = results[richting].geometry.location;
huis_lat=latlng.lat();
huis_lng=latlng.lng();
verander(huis_lat, huis_lng);
document.getElementById("div_overlayStart").style.display="none";
document.getElementById("div_overlayThuis").style.display="block";
}
else if(!address) //no address
{
document.getElementById('alarm1').innerHTML = 'Gelieve u adres in te vullen!';
}
else if(status=='UNKNOWN_ERROR')
{
document.getElementById('alarm1').innerHTML = 'Er ging iets mis (onbekende fout)!';
}
else if(status=='ZERO_RESULTS')
{
document.getElementById('alarm1').innerHTML = 'Er is van deze locatie geen streetview beschikbaar!';
}
}
});
});
});
//+1 one for the array results[richting].geometry.location
function verhoog(){
var address=document.getElementById("address").value;
richting++;
//e.preventDefault();
GMaps.geocode({
address: $('#address').val().trim(),
callback: function(results, status)
{
if(status=='OK'){
var latlng = results[richting].geometry.location;
huis_lat=latlng.lat();
huis_lng=latlng.lng();
verander(huis_lat, huis_lng);
document.getElementById("div_overlayStart").style.display="none";
document.getElementById("div_overlayThuis").style.display="block";
}
}
});
}
</script>
Check if the panorama (streetview) for these X/Y coordinates is visible (not grey). I use the function getPanoramaByLocation to determine this. This returns a status like the previous one. If there are ZERO_RESULTS (=grey zone) it activates the function verhoog() that increments the array of results by 1.
<script type="text/javascript">
var map;
function verander(google_lat, google_lng) {
var bryantPark = new google.maps.LatLng(google_lat, google_lng);
//CHECK FOR GREY ZONE
var client = new google.maps.StreetViewService();
client.getPanoramaByLocation(bryantPark, 50, function(result, status) {
if (status == "ZERO_RESULTS") {
verhoog();
}
else if(status == "OK")
{
var panoramaOptions =
{
position:bryantPark,
pov: {
heading: 185,
pitch:0,
zoom:1,
},
panControl : false,
streetViewControl : false,
mapTypeControl: false,
overviewMapControl: false ,
linksControl: false,
addressControl:false,
zoomControl : false,
}
map = new google.maps.StreetViewPanorama(document.getElementById("map_canvas"), panoramaOptions);
map.setVisible(true);
}
else if(status=='UNKNOWN_ERROR')
{
alert("Er ging iets mis");
}
});
}
</script>
I have a code:
<script src="http://maps.google.com/maps?file=api&v=2.s&key=ABQIAAAA7DHqr4azRz3GFI1rF3F05RTzDhEz38nzyWFNvKs6H8gdGpqkAhQDDMdxJ-xDhaiiIJRibJNuURlZOw"
type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
function load() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallZoomControl());
var MapTypes = map.getMapTypes();
MapTypes[0].getName= function() { return "Mapa";}
MapTypes[1].getName = function() { return "Satelitarna";}
MapTypes[2].getName = function() { return "Hybrydowa";}
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(52.7592485, 19.4559833), 6);
var marker = new GMarker(new GLatLng(54.1943219, 16.1714908));
map.addOverlay(marker);
}
}
//]]>
</script>
</head>
<body onload="load()" onunload="GUnload()">
<div id="map" style="width: 500px; height: 400px"></div>
</body>
Variable "marker" is responsible for mark place on map. Now I must to enter coordinates.
I need mark city, but name of the city, no coordinates.
Look into the geocoding API: http://code.google.com/intl/sv-SE/apis/maps/documentation/geocoding/.