creating a google map that is connected to database - javascript

I am trying to create a google map. the latitude and the longitude are from the database so I had to put those in a textbox then get its value in the script. I tried doing so but it doesn't work will you help me with this one; here's my JavaScript:
function initMap() {
var lat = document.getElementById('lat');
var lang = document.getElementById('lang');
var uluru = {lat: lat, lng: lang };
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
}
Here's the html:
<input type="text" style="display: none" id="lat" value="7.8383054" />
<input type="text" style="display: none" id="lang" value="123.2966657" />
<div id="map" ">
</div>
JSfiddle

the "numbers" in the text fields are access using the .value property:
the lat/lng in a google.maps.LatLngLiteral must be numbers. (without the parseFloat the API throws these errors:
InvalidValueError: setCenter: not a LatLng or LatLngLiteral: in property lat: not a number
InvalidValueError: setPosition: not a LatLng or LatLngLiteral: in property lat: not a number
var lat = parseFloat(document.getElementById('lat').value);
var lang = parseFloat(document.getElementById('lang').value);
You need to actually call the initMap method (your fiddle isn't doing this)
updated fiddle
code snippet:
html,
body,
#map {
height: 100%;
width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap" async defer></script>
<input type="text" id="lat" value="7.8383054" />
<input type="text" id="lang" value="123.2966657" />
<div id="map" ">
</div>
<script>
function initMap() {
var lat = parseFloat(document.getElementById('lat').value);
var lang = parseFloat(document.getElementById('lang').value);
var uluru = {lat: lat, lng: lang };
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
}
</script>

Try:
var lat = document.getElementById('lat').value;
var lang = document.getElementById('lang').value;

Not really sure where your problem lies aside from not actually using the value of the text inputs or calling the function that returns those values but perhaps something long these lines might help get you started. If you are needing the user to enter different lat/lng coordinates then you would also need an event handler assigned to listen for changes or a button to submit the new coordinates.
<?php
/*
*/
?>
<!doctype html>
<html>
<head>
<title>Google maps</title>
<script src='https://www.google.com/jsapi' charset='utf-8'></script>
<script src='https://maps.google.co.uk/maps/api/js?key=APIKEY' charset='utf-8'></script>
<script type='text/javascript' charset='utf-8'>
function initMap() {
var uluru = {
lat: document.getElementById('lat').value,
lng: document.getElementById('lang').value
};
var options={
zoom: 4,
center: uluru
};
var map = new google.maps.Map( document.getElementById('map'), options );
var marker = new google.maps.Marker({
position: uluru,
map: map
});
}
document.addEventListener( 'DOMContentLoaded', initMap, false );
</script>
<style type='text/css' charset='utf-8'></style>
</head>
<body>
<div id='map'></div>
<div>
<input type='text' id='lat' value='7.8383054' />
<input type='text' id='lang' value='123.2966657' />
</div>
</body>
</html>

call initMap() function in body tag. it will load the map, the most important thing do you have api key ? you also need ssl to use google maps. means your url must be https://yourdomain.com
body onload="initMap()"

Related

How Do I Take An Input From A Textbox And Use It To Search For a Location On Google Maps?

I am working on a project and one of the goals is for the user to put a location's name into a textbox and press a button to search for a location on a Google map.
<h2>How to Use</h2>
<p>To use this program, enter a location then click the button to search for it.</p>
<h2>Search Location</h2>
Location: <input type="text" id="myText" value="">
<!-- This creates a textbox --->
<button onclick="searchFunction()">Search</button>
<!-- This creates a button --->
<p id="demo"></p>
<script>
function searchFunction() {
var location = document.getElementById("myText").value;
}
</script>
<style>
#map {
height: 400px;
width: 100%;
}
</style>
</head>
<body>
<h1>Google Map</h1>
<div id="map"></div>
<script>
function initMap() {
var options = {
zoom: 12,
center: {
lat: 39.7684,
lng: -86.1581
}
}
var map = new google.maps.Map(document.getElementById('map'), options);
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBhrDQVoc_0FJx4Hy4tsFMKtmX78VNTUhw&callback=initMap">
</script>
<script>
if (location == "Children's Museum") {
function initMap() {
var options = {
zoom: 12,
center: {
lat: 39.810230,
lng: -86.158882
}
}
var map = new google.maps.Map(document.getElementById('map'), options);
var locationTestPosition = {
lat: 39.810230,
lng: -86.158882
};
var marker = new google.maps.Marker({
position: locationTestPosition,
map: map
});
}
</script>
}
This is the code that I currently have. The idea is that the user will insert a place's name and then using an if/else statement, the code will place a marker on the map at the proper coordinates. I cannot seem to get it to work though. I am new to HTML and JavaScript, so this is a lot of learning for me.

Uncaught ReferenceError: google is not defined (using Google Maps API)

I'm building a site using Django and when I wanted to put a map with markers(which coordinates I pull from database) it refuses to show the markers, throwing out the error:
Uncaught ReferenceError: google is not defined
On every single occurance of:(3rd block)
var map = google.maps.Map(document.getElementById('map'));
Here's the whole code:
<div id="map" style="height: 60%"></div>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 53.132330, lng: 23.159630},
zoom: 12
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDIOOtr2iADzkBWq3r48fHiZRvnAFcWxHY&callback=initMap"
async defer></script>
{% for place in recent_attraction %}
<script>
var map = google.maps.Map(document.getElementById('map'));
function setMarker() {
var latlng = {lat: {{place.gps_x}}, lng: {{place.gps_y}}}
var marker = new google.maps.Marker({
position: latlng,
map: map
})
}
</script>
{% endfor %}
Your reference error seems to be caused by the order that you have your code executing.
Additionally you could create a function to handle adding your markers. I am at work so I cannot test the following code, but it should get you on the right path.
<div id="map" style="height: 60%"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDIOOtr2iADzkBWq3r48fHiZRvnAFcWxHY&callback=initMap" async defer></script>
<script>
var map;
function setMarker(lat, long) {
var latlng = {lat: lat, lng: long}
var marker = new google.maps.Marker({
position: latlng,
map: map
});
}
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 53.132330, lng: 23.159630},
zoom: 12
});
}
</script>
{% for place in recent_attraction %}
<script>
setMarker({{place.gps_x}},{{place.gps_y}});
</script>
{% endfor %}
The problem in the title was removed by moving var map = google.maps.Map(document.getElementById('map')); inside the function. That didn't remove the problem completely, as I still didn't get the markers on my map. The solution was to move the code inside a single block and a single function, like this:
<div id="map" style="height: 60%"></div>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 53.132330, lng: 23.159630},
zoom: 12
});
{% for place in recent_attraction %}
var latlng = {lat: {{place.gps_x}}, lng: {{place.gps_y}}}
var marker = new google.maps.Marker({
position: latlng,
map: map
});
{% endfor %}
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDIOOtr2iADzkBWq3r48fHiZRvnAFcWxHY&callback=initMap"
async defer></script>
Thanks to user Willem Van Onsem.

Checkbox Toggle for Multiple GroundOverlays

What am I missing here? I have been staring at this thing for almost 3 days now, and cannot figure out what I am doing wrong. I have tried countless examples from various parts of the web, and the documentation isnt making much sense - but then again, letters are starting to run together. Any pointers would be helpful!
The below is what I amy trying to get to work. I have two groundoverlay images, with two checkboxes. What I would like to have happen is if the box is checked, the overlay shows. If the box is unchecked, the overlay goes away. Simple right?
<body onload="initialize()">
<div id="controls">
<input name="ckc1" onclick="showcov(rmap1,ckc1);" type="checkbox" checked="true">White Tanks</input>
<input name="ckc2" onclick="showcov(rmap2,ckc2);" type="checkbox" checked="true">Scottsdale</input>
</div>
<div id="map_canvas"></div>
<script language="javascript" type="text/javascript">
var map;
var rmap1,mk1,ckc1;
var rmap2,mk2,ckc2;
function initialize() {
var coord = new google.maps.LatLng( 33.5783309936523,-112.573112487793);
var map = new google.maps.Map(document.getElementById('map_canvas'), {
mapTypeId: google.maps.MapTypeId.TERRAIN,
center: {lat: 33.5783309936523, lng:-112.573112487793},
zoom: 8
});
//White Tanks
var boundaries1 = new google.maps.LatLngBounds(
new google.maps.LatLng( 32.22935,-114.1923),
new google.maps.LatLng( 34.92731,-110.9539));
rmap1 =new google.maps.GroundOverlay("RM77B714BB9248_1.png", boundaries1);
rmap1.setMap(map);
mk1 =new google.maps.Marker({position:new google.maps.LatLng( 33.57832983,-112.57310897),map:map,title:'462.550 Mhz at 50 Watts',draggable:false,zIndex:1});
//Scottsdale
var boundaries2 = new google.maps.LatLngBounds(
new google.maps.LatLng( 32.36672,-113.4623),
new google.maps.LatLng( 35.06469,-110.2188));
rmap2 =new google.maps.GroundOverlay("RM77B714BB9248_4.png", boundaries2);
rmap2.setMap(map);
mk2 =new google.maps.Marker({position:new google.maps.LatLng( 33.715703,-111.840549),map:map,title:'462.600 Mhz at 20 Watts',draggable:false,zIndex:1});
}
//Checkbox Function
function showcov(m,v){if(v.checked) m.setMap(map); else m.setMap(null);}
</script>
</body>
The one below works just fine - but it's only one layer. I'm not sure what I am missing, but I'm sure is something simple as I have little experience with JS and mapping in this fashion.
<script type="text/javascript">
var map;
var rmap1,mk1;
function initialize() {
var coord = new google.maps.LatLng( 33.7157020568848,-111.840545654297);
var myOptions = {zoom: 7,center: coord, mapTypeId:
google.maps.MapTypeId.ROADMAP};
map = new google.maps.Map(document.getElementById("map_canvas"),myOptions );
var boundaries1 = new google.maps.LatLngBounds(new google.maps.LatLng( 32.36672,-113.4623), new google.maps.LatLng( 35.06469,-110.2188));
rmap1 =new google.maps.GroundOverlay("RM77B714BB9248_4.png", boundaries1);
rmap1.setMap(map);
mk1 =new google.maps.Marker({position:new google.maps.LatLng( 33.715703,-111.840549),map:map,draggable:false,zIndex:1});
rmap1.setMap(map);
}
function showcov(m,v){if(v.checked) m.setMap(map); else m.setMap(null);}
</script></head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%;height:80%"></div>
<div style="width:100%;height:10%">
<table width="100%"><tr><th colspan="2">Scottsdale 450 MHz**</th></tr><tr> <td bgcolor="#E0E0E0" colspan="2"><form name="form2">
<input type="checkbox" name="ckc1" checked="true" onclick="showcov(rmap1,ckc1);">Scottsdale 450 MHz**</input>
<input type="checkbox" name="ckm1" checked="true" onclick="showcov(mk1,ckm1);">Scottsdale</input>
</form></td></tr></table></div></body>
You have two issues:
Uncaught TypeError: Cannot read property 'checked' of undefined. you need to pass a reference to the checkbox into the function (this works or remove the declaration of the javascript variable so the automatically created reference to the HTML element can be used, as you did in your "working" example).
var rmap1,mk1; // ckc1;
var rmap2,mk2; // ckc2;
<input id="ckc1" onclick="showcov(rmap1,ckc1);" type="checkbox" checked="true" />White Tanks
<input id="ckc2" onclick="showcov(rmap2,ckc2);" type="checkbox" checked="true" />Scottsdale
Your map variable (at least the version that is initialized) is local to the initialize function, remove the var before it to initialize the global version (which is the scope in which HTML click listeners run), the same as you do in your "working" version of the code.
var map;
function initialize() {
var coord = new google.maps.LatLng( 33.5783309936523,-112.573112487793);
map = new google.maps.Map(document.getElementById('map_canvas'), {
mapTypeId: google.maps.MapTypeId.TERRAIN,
center: {lat: 33.5783309936523, lng:-112.573112487793},
zoom: 8
});
proof of concept fiddle
code snippet:
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="controls">
<input id="ckc1" onclick="showcov(rmap1,ckc1);" type="checkbox" checked="true" />White Tanks
<input id="ckc2" onclick="showcov(rmap2,ckc2);" type="checkbox" checked="true" />Scottsdale
</div>
<div id="map_canvas"></div>
<script language="javascript" type="text/javascript">
var map;
var rmap1, mk1;
var rmap2, mk2;
function initialize() {
var coord = new google.maps.LatLng(33.5783309936523, -112.573112487793);
map = new google.maps.Map(document.getElementById('map_canvas'), {
mapTypeId: google.maps.MapTypeId.TERRAIN,
center: {
lat: 33.5783309936523,
lng: -112.573112487793
},
zoom: 8
});
//White Tanks
var boundaries1 = new google.maps.LatLngBounds(
new google.maps.LatLng(32.22935, -114.1923),
new google.maps.LatLng(34.92731, -110.9539));
rmap1 = new google.maps.GroundOverlay("https://www.lib.utexas.edu/maps/historical/newark_nj_1922.jpg", boundaries1);
rmap1.setMap(map);
mk1 = new google.maps.Marker({
position: new google.maps.LatLng(33.57832983, -112.57310897),
map: map,
title: '462.550 Mhz at 50 Watts',
draggable: false,
zIndex: 1
});
//Scottsdale
var boundaries2 = new google.maps.LatLngBounds(
new google.maps.LatLng(32.36672, -113.4623),
new google.maps.LatLng(35.06469, -110.2188));
rmap2 = new google.maps.GroundOverlay("https://www.lib.utexas.edu/maps/historical/newark_nj_1922.jpg", boundaries2);
rmap2.setMap(map);
mk2 = new google.maps.Marker({
position: new google.maps.LatLng(33.715703, -111.840549),
map: map,
title: '462.600 Mhz at 20 Watts',
draggable: false,
zIndex: 1
});
}
//Checkbox Function
function showcov(m, v) {
if (v.checked) m.setMap(map);
else m.setMap(null);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
You need to pass a reference of checkbox to showcov() like this
<input name="ckc1" onclick="showcov(rmap1,this);" type="checkbox" checked="true">White Tanks</input>
<input name="ckc2" onclick="showcov(rmap2,this);" type="checkbox" checked="true">Scottsdale</input>
But there is one problem, setMap(null) not only removes the groundOverlay but also destroys it so you cannot add them again using setMap() that's why when you un-mark and then re-mark again overlay won't appear. To make it work you need to again create a new overlay object and set it on the map using setMap(map)
I think a better way would be not to remove but simple hide it using setOpacity().That way you don't need to re-create overlays
function showcov(m,v){
if(v.checked) {
//m.setMap(map);
m.setOpacity(1);
else {
//m.setMap(null);
m.setOpacity(0);
}
}
On android you may use much easier setVisible(true) and setVisible(false) but unfortunately those functions are not available for the web version

Google Map does not show the map with given langLat

I have the following code to generate a Google Map based on the given latLang , but it does not show any map.
I get the latLang from DB and store it in a hidden input, the using document.getElementById() I get the value and assign it to the map. But it fails? Why?
(34.686298727073016, 50.92648297548294)
Here is the Javascript Code to Generate the map:
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&language=fa"></script>
<div id='map-canvas' style="width: 500px; height: 500px; border-radius: 10px; -webkit-border-radius: 10px; -moz-border-radius: 10px;">
</div>
<script type="text/javascript">
function initialize() {
var myLatlng = new google.maps.LatLng(document.getElementById('mapPosition').value);
var mapOptions = {
zoom: 8,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'منطقه مورد نظر در نقشه'
});
var infowindow = new google.maps.InfoWindow({
content: "<B>نقطه مورد نظر خود را در نقشه کلیک کنید</B>"
});
/*
google.maps.event.addListener(map, 'click', function(event) {
console.log(event);
marker.setPosition(event.latLng);
document.getElementById('mapPosition').value = event.latLng;
map.setCenter(event.latLng);
});*/
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<input type="hidden" value="<?php echo $item[0]['latLang']; ?>" name="mapPosition" id="mapPosition" />
The api takes two arguments e.g.
new google.maps.LatLng(-34.397, 150.644)
and it looks like you are passing it one
new google.maps.LatLng(document.getElementById('mapPosition').value);
I would advise looking here for your problem.
Either parse the value
(34.686298727073016, 50.92648297548294)
into two parameters, or have two inputs- one for long and another for lat.
try to give individual lat long values:
myLatLong = new google.maps.LatLng(lat, long)

Google maps marker not showing up

I am new to google maps API and using the code below.
Somehow the marker is not being displayed on the map.
I am using google maps API v3.
.controller('MapCtrl', ['$scope',
function MapCtrl($scope) {
var ll = new google.maps.LatLng(38.895112, -77.036366);
$scope.mapOptions = {
center: ll,
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
$scope.onMapIdle = function() {
if ($scope.myMarkers === undefined){
var marker = new google.maps.Marker({
map: $scope.myMap,
position: ll
});
$scope.myMarkers = [marker, ];
}
};
$scope.markerClicked = function(m) {
window.alert("clicked");
};
}
])
HTML code is as below:
<div ng-app='localAdventuresApp'>
<div ng-controller="MapCtrl">
<div id="map_canvas" ui-map="myMap"
style="height:300px;width:400px;border:2px solid #777777;margin:3px; border:1px solid"
ui-options="mapOptions"
ui-event="{'map-idle' : 'onMapIdle()'}"
>
</div>
<div ng-repeat="marker in myMarkers" ui-map-marker="myMarkers[$index]"
ui-event="{'map-click': 'markerClicked(marker)'}">
</div>
</div>
</div>
Try the following code
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Simple markers</title>
<link href="/maps/documentation/javascript/examples/default.css" rel="stylesheet">
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
function initialize() {
var myLatlng = new google.maps.LatLng(38.895112,-77.036366);
var mapOptions = {
zoom: 4,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Hello World!'
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
In fact, it's for AngularJS + Google MAPS V3 + UI-MAP
If markers are not shown when starting map, it's because map is not still loaded.
I founded one solution for solve this problem :
In HTML you declare ui-event with 'map-tilesloaded' witch is trigger by maps event 'tilesloaded':
<div ui-map="myMap" class="map-canvas"
ui-event="{'map-tilesloaded': 'maploaded()'}"
ui-options="mapOptions">
</div>
<div ng-repeat="marker in myMarkers" ui-map-marker="myMarkers[$index]"
ui-event="{'map-click': 'openMarkerInfo(marker)'}">
</div>
Then in your controller you can add markers :
$scope.maploaded = function() {
$scope.myMarkers.push(new google.maps.Marker({
map: $scope.myMap,
position: new google.maps.LatLng(mylat, mylon)
}));
};

Categories