While I can display, my setcenter/pointer is always at the to left position 0,0.
Why is that so?
Is there something I did not do correctly?
Cheers.
function initializeGMap() {
if (GBrowserIsCompatible()) {
document.getElementById("map_canvas").style.width = $('#gmap').width() + "px";
document.getElementById("map_canvas").style.height = $('#gmap').height() + "px";
var map = new GMap2(document.getElementById("map_canvas"));
var malllat = localStorage.getItem("malllat");
var malllon = localStorage.getItem("malllon");
var point = new GLatLng(malllat, malllon);
var marker = new GMarker(point);
map.addControl(new GSmallMapControl());
map.addOverlay(marker);
map.setCenter(point, 16);
}
}
<div data-role="page" id="gmap">
<div id="mapheader" data-role="header" data-theme="b">
Back
<h1>Google Map</h1>
</div>
<!--div id="map_canvas" style="width: 480px; height: 480px"></div-->
<div id="map_canvas"></div>
</div>
Related
This question already has answers here:
Find center of multiple locations in Google Maps
(4 answers)
Closed 4 years ago.
I have this code:
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<style>
#map_canvas {
border:1px solid transparent;
height: 400px;
width: 100%;
}
</style>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-6 padding_all_right_4">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 padding_all_3">
<h2 class="h2">Atrakcje w okolicy</h2>
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 padding_all_2">
<a href ="#" class="obj-1" id="obj-1">
<div class="apartament_atrakcje">Atrakcja 1 pl</div>
</a>
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 padding_all_2">
<a href ="#" class="obj-2" id="obj-2">
<div class="apartament_atrakcje">Atrakcja 2 PL</div>
</a>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 padding_all_0">
<div class="apartament_mapa">
<div id="map_canvas"></div>
<script>
var locations = [
['Atrakcja 1 pl', 51.73925413, 19.51309225, 1],
['Atrakcja 2 PL', 53.41475000, 14.60220358, 2],
];
var map;
var markers = [];
function init(){
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 10,
center: new google.maps.LatLng(-33.92, 151.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var num_markers = locations.length;
for (var i = 0; i < num_markers; i++) {
markers[i] = new google.maps.Marker({
position: {lat:locations[i][1], lng:locations[i][2]},
map: map,
html: locations[i][0],
id: i,
});
google.maps.event.addListener(markers[i], 'click', function(){
var infowindow = new google.maps.InfoWindow({
id: this.id,
content:this.html,
position:this.getPosition()
});
google.maps.event.addListenerOnce(infowindow, 'closeclick', function(){
markers[this.id].setVisible(true);
});
this.setVisible(false);
infowindow.open(map);
});
}
}
init();
</script>
The script displays 2 points on the google map.
I have a problem with centering the map on these points. Currently, I enter the coordinates of the centering of the map in the page code, however points on the map are added from the CMS and must center automatically :(
Does anyone know how to do it?
Do you need to center on one point? scaisEdge answer will do that for you.
map.setCenter(new google.maps.LatLng(lat, lng));
Else if what you need is to center on the 'center' of those two points. You'll need to calculate the center point between those two and then center on this new LatLong. For that you can check Google Maps Javascript API
and this post of stackoverflow: Find center of multiple locations in Google Maps
You could use setCenter()
map.setCenter(new google.maps.LatLng(lat, lng));
eg for center on the first marker
map.setCenter(new google.maps.LatLng(locations[0][1], locations[0][2]));
I'm trying to reverse geocode an address for an app so that the address shows up in a window at the bottom of the page and in a second window, you see your coordinates, accuracy, speed, and what time the information was updated. When I run my code without the reverse geocoding part, everything runs fine, but when I try to reverse geocode, I not only get nothing in the first window, but the window with coordinates, accuracy, and speed is blank as well. I don't understand why the second window is being affected by my reverse geocoding code and I'm not sure why an address isn't showing up in the first window.
Here is my code:
$(document).on("mobileinit", function() {
//$(document).ready(function(){
console.log('mobileinit');
$.mobile.page.prototype.options.defaultPageTransition = "none";
$.mobile.listview.prototype.options.theme = "a";
$.mobile.toolbar.prototype.options.theme = "a";
$.mobile.toolbar.prototype.options.addBacBtn = "true";
});
var geocoder;
var currentLocation;
function init() {
if (navigator.geolocation) {
//Use the Geolocation API to get current location and track it as you move
navigator.geolocation.watchPosition(showLocation, locationError);
} else {
alert("Geolocation not supported on this device");
return;
}
// Define "click" events for "queryPlaces()" function
$("#policeItem").on("click", function() {
queryPlaces('Police');
});
$("#fsItem").on("click", function() {
queryPlaces('Fire Station');
});
$("#tdItem").on("click", function() {
queryPlaces('Transportation Department');
});
$("#ahItem").on("click", function() {
queryPlaces('Animal Hospital');
});
$("#hospitalItem").on("click", function() {
queryPlaces('Hospital');
});
} //end of init function
function showLocation(location) {
//var temp = "Geocoding Not In Operation... Sorry";
//$('#loc').html(temp);
geocoder = new google.maps.geocoder();
currentLocation = new google.maps.LatLng(location.coords.latitude, location.coords.longitude);
geocoder.geocode({
'location': curentLocation
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
$('#loc').html(results[0].formatted_address);
} else {
$('#loc').html('No address found');
}
} else {
$('#loc').html('Unavailable to determine address');
}
}); //end of geocode method
var info = "Coordinates: " + parseFloat(location.coords.latitude).toFixed(3) + ", ";
info += parseFloat(location.coords.longitude).toFixed(3) + "<br/>";
info += "Accuracy: " + parseFloat(location.coords.accuracy) + " meters" + "<br/>";
info += "Speed: " + parseFloat(location.coords.speed) + " m/s" + "<br/>";
info += "Updated: " + new Date(location.timestamp).toLocaleString();
$('#acc').html(info);
} //end of showLocation function
function locationError(error) {
switch (error.code) {
case error.PERMISSION_DENIED:
alert("Geolocation access denied or disabled. To enable geolocation " + "on your iPhone, go to Settings > General > Location Services");
break;
case error.POSITION_UNAVAILABLE:
alert("Current location not available");
break;
case error.TIMEOUT:
alert("Timeout");
break;
default:
alert("unknown error");
break;
}
}
function updateDist(value) {
$("#distVal").html("" + value + " meters");
}
$(document).on("pagecreate", "#homeView", init);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<!-- Home Page Begins-->
<div id="homeView" data-role="page" data-title="Wildlife Vehicle Collisions" data-theme="a">
<div data-role="header" data-position="fixed" id="header1">
<h1>WVC</h1>
</div>
<div data-role="content">
<img src="images/wildlife-3.jpg" alt="WVC Management" />
<div data-role="controlgroup" data-theme="b" class="ui-content">
Find Nearby
Report Collisions
Videos
Photos
</div>
<!-- links -->
</div>
<!-- content -->
<footer>
<p>© Copyright by resop</p>
</footer>
</div>
<!-- page -->
<!-- findView Page Begins-->
<div id="findView" data-role="page" data-theme="a">
<div data-role="header" data-position="fixed" id="header1">
Home
<h1>What's Nearby</h1>
Settings
</div>
<!--header End-->
<div data-role="content">
<ul data-role="listview" data-inset="true">
<li id="policeItem">Police Departments</li>
<li id="fsItem">Fire Stations</li>
<li id="tdItem">Transportation Departments</li>
<li id="ahItem">Animal Hospitals</li>
<li id="hospitalItem">Hospitals</li>
</ul>
<h2>Current Location</h2>
<div id="loc"></div>
<div id="acc"></div>
</div>
<!-- Content End -->
<div data-role="footer" data-position="fixed" id="footer1">
<div data-role="navbar">
<ul>
<li>Home</li>
<li>Find</li>
<li>Report</li>
<li>Videos</li>
<li>Photos</li>
</ul>
</div>
<!--navbar end-->
</div>
<!--footer end-->
</div>
<!--findView Page End-->
Any help would be greatly appreciated!
Turns out I did need an API key and part of the google maps API Geocode code had been decommissioned. The following code worked:
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=APIKEY&libraries=places"></script>
<style>
#mapDiv { height: 100vh; }
header { position: absolute; background-color: black; color: white; z-index: 1; right: 0; }
</style>
</head>
<body>
<header></header>
<div id="mapDiv"></div>
<script>
var apikey = "AIzaSyDV4cbTEeLmiXaPMIrEwAKB8xFGxvdDS1s",
map;
//runtime
$(document).ready(init);
function init(){
//assign event listeners
//start the app
getLocation();
}
function initMap(lat, lng){
//create Google map
map = new google.maps.Map(document.querySelector("#mapDiv"), {
center: {lat: lat, lng: lng},
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoom: 14
});
}
function getLocation(){
//can we get lat/lng from this device?
if (!navigator || !navigator.geolocation){
//handle error: lat/lng not available
return;
}
//get lat/lng from device
navigator.geolocation.getCurrentPosition(function(pos){
var lat = pos.coords.latitude,
lng = pos.coords.longitude,
url = "https://maps.googleapis.com/maps/api/geocode/json?latlng="+ lat + "," + lng +"&key=" + apikey;
//open Google map centered on device
initMap(lat, lng);
//get location data from Google
$.ajax({url: url})
.done(function(data){
document.querySelector("header").textContent = data.results[0].formatted_address;
});
});
}
</script>
</body>
</html>
I have so far created a template of what i want and have manged to start getting each area to work, still got some work to do but I am currently trying to embed a KML file as a layer for my google map.
Here is my full coding below.
<!DOCTYPE html>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
var markers = [];
function createMarker(latlng, html, map, refnum) {
var latlngtxt = (latlng.lat() + ',' + latlng.lng()).split(',');
$.each(latlngtxt, function(i, v){
v = Math.round(v);
v += v > 0? (i? 'E' : 'N') : (i? 'W' : 'S');
latlngtxt[i] = v.replace(/^-/, '');
});
latlngtxt = latlngtxt.join(', ');
var ref = $.trim($('#reference').val());
//ref = ref? ref + '<br>' : '';
var infowindow = new google.maps.InfoWindow({
content: ref || html //+ '#' + (markers.length + 1) + '<br>' + html + '<br>' + latlngtxt
});
var marker = new google.maps.Marker({
map: map,
position: latlng,
html: html,
infowindow: infowindow
});
marker.addListener('mouseover', function() {
infowindow.open(map, this);
$('#supplementwindow').html(infowindow.content).fadeIn();
});
marker.addListener('mouseout', function() {
infowindow.close();
$('#supplementwindow').fadeOut();
});
markers.push(marker);
}
var up206b = {};
var map;
function trace(message) {
if (typeof console != 'undefined') {
console.log(message);
}
}
up206b.initialize = function() {
var latlng = new google.maps.LatLng(52.136436, -0.460739);
var myOptions = {
zoom: 13,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
up206b.geocode();
}
var ctaLayer = new google.maps.KmlLayer({
url: 'file:///C|/wamp/www/maps/UK County border lines.kml',
map: map
});
var geocoder = new google.maps.Geocoder();
var bounds = new google.maps.LatLngBounds();
up206b.geocode = function() {
/* for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers = []; */
var addresses = [$('#address').val(), $('#address2').val()];
addresses.forEach(function(address, refnum) {
if (address) {
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
createMarker(results[0].geometry.location, address, map, refnum);
bounds.extend(results[0].geometry.location);
map.fitBounds(bounds);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
});
}
jQuery(function($){
$('#removemarker').click(function(){
var tm = $('#themarkers'), si = tm.get(0).options.selectedIndex, $o = $('option', tm).eq(si), i = $o.val();
if(!i){return;}
$.each(markers, function(idx, v){
if(v.html === i){
v.setMap(null);
markers.splice(idx, 1);
return false;
}
});
$o.remove();
bounds = new google.maps.LatLngBounds();
if(markers.length){
$.each(markers, function(i, v){
bounds.extend(v.position);
});
map.fitBounds(bounds);
}
if(markers.length < 2){
map.setZoom(markers.length? 13 : 8);
}
});
$('#themarkers').change(function(){
this.title = this.options[this.options.selectedIndex].title;
var i = this.value;
if(!i){return;}
$.each(markers, function(idx, v){
if(v.html === i){
map.setCenter(v.position);
map.setZoom(10);
return false;
}
});
});
$('#showall').click(function(){
$('#themarkers').get(0).selectedIndex = 0;
if(!markers.length){
map.setCenter(new google.maps.LatLng(52.136436, -0.460739));
map.setZoom(13);
return;
}
map.fitBounds(bounds);
if(markers.length === 1){
map.setZoom(13);
}
});
});
</script>
</head>
<body onload="up206b.initialize()">
<div style="width:300px; height: 500px; float:right; padding-left:10px; padding-right:10px; margin: 50px 90px 50px 75px">
<h1 align="center">Map Search</h1>
<div style="border:1px solid #ccc; background:#e5e5e5; padding:10px;" align="center" >
<form >
<br>
Location 1 <input type="text" id="address">
<br>
<br>
Location 2
<input type="text" id="address2">
<br>
<br>
Reference
<input type="text" id="reference">
<br>
<br>
<input type="button" value="Submit" onClick="up206b.geocode()">
</form>
</div>
<div id="menu" style=" position: absolute; margin: 45px 89px;" >
<select id="Counties">
<option value="">Select County</option>
<option value="bedfordshire">Bedfordshire</option>
<option value="buckinghamshire">Buckinghamshire</option>
<option value="cambridgeshire">Cambridgeshire</option>
<option value="hertfordshire">Hertfordshire</option>
<option value="northamptonshire">Northamptonshire</option>
</select>
</div>
</div>
<div id="map_canvas" style="height: 500px; width: 500px; float:right; margin:20px 75px;"></div>
<div id="supplementwindow" style="border:1px solid #ccc; background:#e5e5e5; align-content:center; float:left; position:absolute; margin:200px 0px 200px 200px; padding: 5px; border-radius: 12px;" >
<input type="button" value="Assign">
</div>
<div id="menu2" style="position: absolute; right: 200px; top: 450px; border: 1px solid #bbb; padding: 5px;
border-radius: 12px;"><select id="themarkers"><option value="">Select Marker</option>
</select><br>
<input type="button" id="showall" title="Or Reset if None" value="Show All"><br>
<input type="button" id="removemarker" value="Remove Marker"></div>
</body>
</html>
The snippet of my code below is where I am trying to embed the KML file as a layer. I have tried using an online server URL with my KML and it doesn't work and also using Wamp as a local host server. Would it actually work with Wamp?
Have I placed to coding in the wrong place, have I written it wrong or missed out something? If anyone could give me some guidance, I would appreciate it thanks.
var ctaLayer = new google.maps.KmlLayer({
url: 'file:///C|/wamp/www/maps/UK County border lines.kml',
map: map
});
According to the documentation, the KmlLayer URL must be publicly accessible.
Overview
The Google Maps JavaScript API supports the KML and GeoRSS data formats for displaying geographic information. These data formats are displayed on a map using a KmlLayer object, whose constructor takes the URL of a publicly accessible KML or GeoRSS file.
proof of concept fiddle
code snippet:
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var kmlLayer = new google.maps.KmlLayer({
map: map,
url: "http://www.geocodezip.com/geoxml3_test/final_map_original_wales1c.xml"
})
google.maps.event.addListener(kmlLayer, 'status_changed', function() {
document.getElementById('status').innerHTML = "KmlStatus=" + kmlLayer.getStatus();
})
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="status"></div>
<div id="map_canvas"></div>
www.bchomescondos.ca/properties/?city=Burnaby&id=261618646
www.bchomescondos.ca/properties/?city=Burnaby&id=261711367
These are just the few of the sample pages where the problem is arising. I am not too proficient with the Google Map API, but still tried to incorporate on my website.
I have added three tabs- one showing the road map, another the street view and the third is the walkscore. While the road map and walk-score is working fine, the street view isn't.
But one strange thing I have noticed is if the page is resized (just for any weird reason) the street view map appears.
I would be very much obliged if anyone helps me with this problem.
The Script
http://pastebin.com/zQTCxez2
<script src="https://maps.googleapis.com/maps/api/js?v=3.19&sensor=true_or_false"></script>
<script>
var geocoder;
var ws_wsid = 'afca921c9778417e8dc16a8236d1f079';
var ws_address = "<?php echo $row['address']; ?>,<?php echo $row['city']; ?>";
var ws_width = '100%';
var ws_height = '400';
var ws_layout = 'vertical';
var ws_commute = 'true';
var ws_transit_score = 'true';
var ws_map_modules = 'all';
var address = "<?php echo $row['address']; ?>,<?php echo $row['city']; ?>";
function initialize() {
var fenway = new google.maps.LatLng( <? php echo $row['latitude']; ?> , <? php echo $row['longtitude']; ?> )
var mapOptions = {
center: fenway,
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
var contentString = '<a class="fancybox-inline" href="#request_form_pop">Request of showing this property</a>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var marker = new google.maps.Marker({
position: fenway,
map: map,
title: ''
});
infowindow.open(map, marker);
google.maps.event.addListener(marker, 'click', function() {});
var panoramaOptions = {
position: fenway,
pov: {
heading: 34,
pitch: 10
}
};
panorama = new google.maps.StreetViewPanorama(document.getElementById('pano'), panoramaOptions);
map.setStreetView(panorama);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
The HTML
http://pastebin.com/fgDRR0MN
<div class="row">
<div class="one columns"></div>
<section class="ten columns tabs" style="margin: 20px 0;">
<ul class="tab-nav">
<li class="active">Google Map</li>
<li> Street View</li>
<li>Walk Score</li>
</ul>
<div class="tab-content active">
<div id="map-canvas" style="height: 400px; border: 0.5px solid #000;">
</div>
</div>
<div class="tab-content">
<div id="pano" style="height: 400px; border: 0.5px solid #000;"></div>
</div>
<div class="tab-content">
<div id="ws-walkscore-tile" style="height: 400px; border: 0.5px solid #000;"></div>
</div>
<script type='text/javascript' src='http://www.walkscore.com/tile/show-walkscore-tile.php'></script>
</section>
<div class="one columns"></div>
</div>
I just wanted to show the street view when that particular tab is clicked.
CSS Files
[http://www.bchomescondos.ca/wp-content/themes/dgdon/css/gumby.css]
[http://www.bchomescondos.ca/wp-content/themes/dgdon/css/style.css]
So, it can be deduced that there is no problem with the map api and it's script. The problem lies with how the CSS tabs are handled.
Thanks duncan for your help. I would open a new question regarding solving this CSS and JS problem.
so far the text is centered the google maps page hugs the left and then the text underneath it remains centered, i just want the map to be centered.
<div id="row1">
<div id="note"><img src="http://www.bristol.gov.uk/sites/default/files/styles/hero_image/public/images/children_and_young_people/resources_for_professionals/head_teachers_and_school_administrators/hr/contact_us/we%20will%20be%20back%20soon-sticky%20note.jpg?itok=08vLR_lO"></div>
<div id = "hours">
Sorry<br>
hours<br>
</div>
<div id="gmap_canvas" style="height:500px; width:600px;"></div>
Below text
</div>
Style:
#row1 {
text-align: center;
}
Google Map JavaScript:
<script type="text/javascript">
function init_map() {
var myOptions = {
zoom: 16,
center: new google.maps.LatLng(20.0820037, -14.26733380000002),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("gmap_canvas"), myOptions);
marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(20.0820037, -14.26733380000002)
});
infowindow = new google.maps.InfoWindow({
content: "<b>Crokson Dine In</b><br/>43 Gill Rd<br/>09521 Hovill"
});
google.maps.event.addListener(marker, "click", function() {
infowindow.open(map, marker);
});
infowindow.open(map, marker);
}
google.maps.event.addDomListener(window, 'load', init_map);
</script>
text-align: center cannot center a block element itself. You need auto margins:
<div
id="gmap_canvas"
style="height:500px; width:600px; margin-left: auto; margin-right: auto;">