Google Maps Javascript API V3 not working - javascript

I have this on the of my .php file
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 15,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function codeAddress(address) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
and along the page I have the div in a modal
<div id="map-canvas"></div>
But the map does not show in the modal... I get no errors on Opera Console and when I try to call the functions [initialize() and or codeAddress("Spain")] through the console it says undifined
I've created a page only for the map for testing and it worked fine.
Any ideas?
==EDIT==
After adding the height to my css file the map is shown with some problems
http://postimg.org/image/mhj9awdez/
Only after a second initialization the map is shown correctly (the initialization must be done with the modal open)

you need to call initialize() function after the loading the js file ...
i think this will help you
<https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&' +
'callback=initialize';>>
<!DOCTYPE html>
<html>
<head>
<title>Asynchronous Loading</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script>
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644)
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
}
function loadScript() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&' +
'callback=initialize';
document.body.appendChild(script);
}
window.onload = loadScript;
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>

Related

Google Maps API - Auto Center and Auto Zoom

I am having trouble fitting auto center and auto Zoom on a map created from a CSV file that goes into a PHP array then transferred into JavaScript--code as follows -
<!DOCTYPE html>
<?php
include "getCsvData.php"; // this is where we put the data into a PHP array called $dataArray;
// now we exit the PHP and do the HTML including our Javascript...
?>
<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>Google Maps JavaScript API v3 Example: Geocoding Simple</title>
<link href="http://code.google.com/apis/maps/documentation/javascript/examples/standard.css" rel="stylesheet"
type="text/css"/>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder;
var map;
var markers = [];
var image = {
url: 'src/icon' + 'a.png'
,
};
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(0, 0);
var myOptions = {
zoom: 7,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
<?php
for($i = 0, $j = count($postcodes); $i < $j - 1 ; $i++) {
?>
addPostCode(<?php echo str_replace(array('[', ']'), '', json_encode($postcodes[$i])); ?>);
<?php } ?>
}
function addPostCode(zip) {
geocoder.geocode({'address': zip}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
icon: image,
position: results[0].geometry.location,
name: zip
});
markers.push(marker);
// latlng.extend(marker.position);
} else if (status === google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
setTimeout(function () {
Geocode(address);
}, 200);
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="height:90%"></div>
</body>
</html>
I have found I need to use fitBounds but I cannot seem to get it working either the page doesn't load or it only center on one result and then I have to zoom out.
Here's for my setup for such case, Note that I use window here so I can access Google objects from any scope. You need to add each marker to mapBounds using extend() method and passing the position.
$(function(){
window.gMap = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 10,
center: {lat: 37.769, lng: -122.446}
});
var addresses = ["296 Gingerbread St", "383 Hoskins Ct", "1608 Liege Dr", "519 Mandalay Ct", "342 Pleasant Summit Dr", "1757 Quiver Point Ave", "174 Rising Mesa Ct", "26 Silica Sand St", "192 Thunder Plains Way", "277 Timber Hollow St", "367 Via Pacifico", "382 Washtenaw St"];
var timeOut = 0;
$.each(addresses, function(i, address){
setTimeout(function(){ addMarker(address) }, timeOut);
timeOut = timeOut+1600;
});
});
function addMarker(address) {
geoCoder.geocode({'address': address}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
gMap.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: gMap,
position: results[0].geometry.location,
});
markers.push(marker);
//extend the bounds to include each marker's position
mapBounds.extend(marker.position);
//now fit the map to the newly inclusive bounds
gMap.fitBounds(mapBounds);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
#map-canvas {
width:80%;
padding-left:15px;
padding-right:15px;
height:300px;
border:2px solid #e8e8e8;
border-radius:4px;
margin:auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function initMap() {
window.mapBounds = new google.maps.LatLngBounds();
window.geoCoder = new google.maps.Geocoder();
window.markers = [];
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>
<div id="map-canvas"></div>

API Google Maps Javascript Address to LatLng

I'm trying to use the Google Maps API on my website, and I want to convert an Address inputted by the user to LatLng and show the location on the map. I already know that I need to use the Geocoding function, but for some reason it's not working. Here's the code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?key=AIzaSyBSkRxYKDW33Zng3Kmp_7IC_nom9JEEVwc&sensor=FALSE">
</script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
}
function moradaToLatLng(morada){
var geocoder = new google.maps.Geocoder();
if (geocoder) {
alert("1");
geocoder.geocode({
'address': address
}, function (results) {
alert("2");
map.setCenter(results[0].geometry.location);
map.setZoom(16);
var m = document.getElementById("morada").innerHTML = results[0].geometry.location;
//criarPopup(address, results[0].geometry.location);
});
}
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:80%"></div>
<div id="form">
<input type="text" id="morada" value="Morada">
<button id="btnMorada" onclick="moradaToLatLng(morada.value)">Ok</button>
</div>
</body>
</html>
For some reason, it doesn't enter the function and display alert("2");
EDIT.: I put all of my code
Add this line to your code:
var address = document.getElementById('morada').value;
as following:
function moradaToLatLng(morada) {
var address = document.getElementById('morada').value;
var geocoder = new google.maps.Geocoder();
if (geocoder) {
alert("1");
geocoder.geocode({
'address': address
}, function (results) {
alert("2");
map.setCenter(results[0].geometry.location);
map.setZoom(16);
var m = document.getElementById("morada").innerHTML = results[0].geometry.location;
//criarPopup(address, results[0].geometry.location);
});
}
}

Nearby places in google maps APIs

I am trying to write a program in javascript related to finding my place by using google maps APIs and the browser navigator and then put a marker on the place.My code works properly for this part. But for the second part that I want to find the nearby places and put markers on them does not work and I cannot find the problem. It gives me an error about the map variable. It seems the code breaks and cannot get the map variable for performsearch function. Any idea would be highly appreciated?
The code is as below:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 75% }
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC2MndnCGBXqDolsrQYhNdVyXqsk0NRm8Q&sensor=true&libraries=places">
</script>
<script type="text/javascript" >
var map;
function handleSearchResults(results, status)
{
console.log(results);
document.write
if (status == google.maps.places.PlacesServiceStatus.OK)
{
for(var i = 0; i<results.length; i++)
{
var marker = new google.maps.Marker(
{
position: results[i].geometry.Location,
map:map,
icon: results[i].icon
});
}
}
}
function performSearch()
{
var request = {
bounds: map.getBounds(),
name: "McDonald's"
};
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, handleSearchResults(results, status));
}
function initialize(location)
{
var myLatlng = new google.maps.LatLng(location.coords.latitude, location.coords.longitude);
var mapOptions =
{
center: myLatlng,
zoom: 9
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
var marker = new google.maps.Marker(
{
position: myLatlng,
map: map,
title: "My place"
});
service = new google.maps.event.addListenerOnce(map, 'bounds_changed', performSearch());
}
$(document).ready(function()
{
navigator.geolocation.getCurrentPosition(initialize);
});
</script>
</head>
<body>
<div id="map-canvas"/>
</body>
</html>
There are several issues. Fixed code(modifications are commented inside):
var map;
function handleSearchResults(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var marker = new google.maps.Marker({
//typo: it must be location not Location
position: results[i].geometry.location,
map: map,
icon: results[i].icon
});
}
}
}
function performSearch() {
var request = {
bounds: map.getBounds(),
name: "McDonald's"
};
var service = new google.maps.places.PlacesService(map);
//use only the name of the function as callback-argument
service.nearbySearch(request, handleSearchResults);
}
function initialize(location) {
var myLatlng = new google.maps.LatLng(location.coords.latitude,
location.coords.longitude);
var mapOptions = {
center: myLatlng,
zoom: 9
};
//removed the var-keyword(otherwise map is not global accessible)
map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: "My place"
});
//again: use only the name of the function as callback-argument
service = new google.maps.event.addListenerOnce(map,
'bounds_changed',
performSearch);
}
$(document).ready(function () {
navigator.geolocation.getCurrentPosition(initialize);
});
But note: geolocating may fail, currently the map will never be initialized when it fails. You better separate the map-creation from the geolocating

Click action is not working for the below code in Google Maps

Can anyone please tell me what is wrong with this code? The map loads but a user's click action does not open up the info_window or re-center the map to the clicked point.
I want the address of a location to pop-up as an info_window whenever the user clicks on a map.
<!DOCTYPE html>
<html>
<head>
<title>Accessing arguments in UI events</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body {
height: 100%;
margin: 0px;
padding: 0px
}
#map-canvas {
height: 60%; width: 60%
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3&libraries=geometry&key=MY_KEY&sensor=true">
</script>
<script type="text/javascript">
var geocoder;
var map;
var info_win;
var pos;
var marker;
function initialize()
{
google.maps.visualRefresh = true;
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
google.maps.event.addListener(map, 'click', function(evt) {
pos = evt.latLng;
map.setCenter(pos);
geocoder.geocode({'location': pos}, function(results, status)
{
if(status == google.maps.GeocoderStatus.OK)
{
marker = new google.maps.Marker
({
map: map,
position: pos
});
info_win = new google.maps.InfoWindow
({
content: results[0].formatted_address,
});
info_win.open(map,marker);
}
else
{
alert("Could not load");
}
});
});
}
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
First problem: You are adding the click listener to the map outside of the initialize function, so it is being added before the map is initialized:
<script type="text/javascript">
var geocoder;
var map;
var info_win;
var pos;
var marker;
function initialize()
{
google.maps.visualRefresh = true;
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
google.maps.event.addListener(map, 'click', function() {
pos = map.getPosition();
map.setCenter(pos);
geocoder.geocode({'location': pos}, function(results, status)
{
marker = new google.maps.Marker
({
map: map,
position: pos
});
info_win = new google.maps.InfoWindow
({
content: results[0].formatted_address,
});
infowindow.open(map,marker);
});
});
}
</script>
After that you will find that a google.maps.Map object does not have a getPosition method. It does have a getCenter method, but you probably want to use the latLng property of the click event instead.
google.maps.event.addListener(map, 'click', function(evt) {
pos = evt.latLng;
map.setCenter(pos);
And fix the code that opens the info_win to open the google.maps.InfoWindow that you created:
info_win = new google.maps.InfoWindow
({
content: results[0].formatted_address,
});
info_win.open(map,marker);

Need to add "directions to here" link in infowindow

I'm new to both Google Maps and Javascript but have to get this issue solved! I have an .html file with a google map of our client's location loaded into the map_canvas div. Through tutorials, I have been able to figure out how to write enough Javascript to get the map to function, have a custom marker and and infowindow that pops up when you click on it. The only part left is to have a link inside the infowindow that says "directions to here" and there's a text field that the user can type in their starting address. I'm seeing plenty of documentation to help me write my own code on the Google Developer's site but I am not advanced enough to do this. Can anyone help me figure out how to do this? Here is my Javascript:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function initialize()
{
var latlng = new google.maps.LatLng(33.929011, -84.361);
var myOptions = {
zoom: 15,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(33.929011, -84.361),
map: map,
title: 'Atlanta/Sandy Springs',
clickable: true,
icon: 'images/mapmarker.png'
});
var infowindow = new google.maps.InfoWindow({
content: 'client address'
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
}
</script>
There are several pieces I added. First, you need a better HTML form inside the infowindow, since I only put in the basic parts and it won't respond when you press Enter.
Next, I added a geocoder because the directions Service won't take "human readable" addresses, only latLng coordinates. The geocoder converts the two. Finally, the directions Service and Display are added. The directions text goes into a div (directionsPanel).
See the working fiddle or use this code:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
html, body {
margin: 0;
padding: 0;
height: 100%
}
#map_canvas {
margin: 0;
padding: 0;
width: 50%;
height: 100%
}
#directionsPanel {
position: absolute;
top: 0px;
right: 0px;
width: 50%
}
</style>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder;
var directionsService;
var directionsDisplay;
function initialize() {
var latlng = new google.maps.LatLng(33.929011, -84.361);
var myOptions = {
zoom: 15,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(33.929011, -84.361),
map: map,
title: 'Atlanta/Sandy Springs',
clickable: true
});
var infowindow = new google.maps.InfoWindow({
content: "Your address: <input id='clientAddress' type='text'>"+
"<input type='button' onClick=getDir() value='Go!'>"
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker);
});
geocoder = new google.maps.Geocoder();
directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer({
suppressMarkers: false
});
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById("directionsPanel"));
}
function getDir() {
geocoder.geocode({
'address': document.getElementById('clientAddress').value
},
function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var origin = results[0].geometry.location;
var destination = new google.maps.LatLng(33.929011, -84.361);
var request = {
origin: origin,
destination: destination,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
} else {
document.getElementById('clientAddress').value =
"Directions cannot be computed at this time.";
}
});
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas"></div>
<div id="directionsPanel"></div>
</body>
</html>

Categories

Resources