I have a website that loads 3 seperate "views" of a location via Google Maps, Street and Places.
Please see my code below:
I have finally gotten Maps and Street view to work properly but am struggling a bit with this one.
I have a tab that displays the same as map but with places added.
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?v=3&key=....&sensor=false&callback=initializeMap"></script>
<script type="text/javascript">
var myLattitude = <?php echo $data["lattitude"]; ?>;
var myLongitude = <?php echo $data["longitude"]; ?>;
var poiMap;
var infowindow;
function initializePoi() {
var poiCentre = new google.maps.LatLng(myLattitude, myLongitude);
poiMap = new google.maps.Map(document.getElementById('poi-canvas'), {
center: poiCentre,
zoom: 15
});
var request = {
location: poiCentre,
radius: 500,
types: ['store']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(poiMap);
service.nearbySearch(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: poiMap,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(poiMap, this);
});
}
Now This initializes properly but the console throws the following error:
TypeError: google.maps.places is undefined
I just want to know why I get this error, I like having clean errorless code.
The places do actually show up properly and everything.
You should add the option libraries=places in the Google API URL
In your case you should replace the following:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&key=....&sensor=false&callback=initializeMap"></script>
With this:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&key=....&sensor=false&callback=initializeMap&libraries=places"></script>
Look at the end of the src=""
Now, you have to use https instead of http.
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&key=....&sensor=false&callback=initializeMap&libraries=places"></script>
Everything else is same as previous answer mentioned.
Since the top answer addresses the vanilla version, this is for those using google-maps-react:
add libraries: ['places'] to your GoogleMapReact Component:
<GoogleMapReact
bootstrapURLKeys={{ key: apiKey, libraries: ['places'] }}
...
/>
If you are using React.
import { Wrapper as MapsWrapper } from "#googlemaps/react-wrapper";
// Note libraries prop.
<MapsWrapper apiKey={'YOUR_API_KEY'} libraries={['places']}>
<ChildComponent />
</MapsWrapper>
Related
I am currently displaying markers on a Google Map successfully, but want to overlay a different set of markers in a different colour for something else but I'm a bit stuck on how to do it.
I am getting the data into the $markers array from a database as follows:
while($row = $result->fetch_row())
{
$rows[]=$row;
$markers[$key] = trim($row[12]).','.trim($row[13]).','.trim($row[10]).','.trim($row[9]).','.trim($row[8]).','.trim($row[4]).','.trim($row[6]).','.trim($row[3]);
$key = $key +1;
}
Where the $row[""] is the data from the database including lat and lon for the marker locations.
The magic then happens in here:
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=<?=$api_key?>">
</script>
<script type="text/javascript">
var map;
var marker = {};
function initialize() {
var mapOptions = {
center: { lat: 20.1788823, lng: 13.8262155},
zoom: 2
};
map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
var markers = [];
<?php
$counter = 0;
foreach ($markers as $index => $list){
$marker_details = explode(',',$list);
echo 'markers["m'.($index-1).'"] = {};'."\n";
echo "markers['m".($index-1)."'].lat = '".$marker_details[0]."';\n";
echo "markers['m".($index-1)."'].lon = '".$marker_details[1]."';\n";
$counter++;
}
?>
var totalMarkers = <?=$counter?>;
var i = 0;
var infowindow;
var contentString;
for (var i = 0; i<totalMarkers; i++){
contentString = '<div class="content">'+
'<h2 class="firstHeading">'+markers['m'+i].name+'</h2>'+
'<div class="bodyContent">'+
'<p>'+markers['m'+i].content+'</p>'+
'</div>'+
'</div>';
infowindow = new google.maps.InfoWindow({
content: contentString
});
marker['c'+i] = new google.maps.Marker({
position: new google.maps.LatLng(markers['m'+i].lat,markers['m'+i].lon),
icon: {
url: "https://maps.google.com/mapfiles/ms/icons/red.png"
},
map: map,
title: markers['m'+i].name,
infowindow: infowindow
});
//console.log(markers['m'+i].lat+','+markers['m'+i].lon);
google.maps.event.addListener(marker['c'+i], 'click', function() {
for (var key in marker){
marker[key].infowindow.close();
}
this.infowindow.open(map, this);
});
}
}
function panMap(la,lo){
map.panTo(new google.maps.LatLng(la,lo));
}
function openMarker(mName){
//console.log(marker);
for (var key in marker){
marker[key].infowindow.close();
}
for (var key in marker){
if (marker[key].title.search(mName) != -1){
marker[key].infowindow.open(map,marker[key]);
}
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
And finally it is rendered with this:
<div id="map-canvas"></div>
I have tried reading the second set of data from another data into $markers2[$key] but I'm then stuck at what to do next, I've tried quite a few different things (too many to list here!) but it either fails to render the new markers of fails to render anything at all on the map.
Any pointers in the right direction would be helpful. I'm not too familiar with javascript unfortunately.
Ok, I found the problem, the issue was that I was creating another "new" map each time and needed to remove the additional instances of :
map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
Now the additional markers with the new data display correctly.
Thanks for all the downvotes, it really does concentrate the mind on finding the solution yourself!
I have problem coding the google maps API for my personal website. The google maps doesn't work until I refresh the browsers. Below are the scripts for google maps.
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false&v3"></script>
<script type="text/javascript" src="<?php echo get_bloginfo('template_url'); ?>/js/mk.js"></script>
<script type="text/javascript">
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 13,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map"), myOptions);
}
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 MarkerWithLabel({
position: results[0].geometry.location,
map: map,
labelContent: address,
labelAnchor: new google.maps.Point(22, 0),
labelClass: "labels", // the CSS class for the label
labelStyle: {opacity: 1.0}
});
} else {
//alert("Geocode was not successful for the following reason: " + status);
}
});
}
initialize();
codeAddress("<?php
global $post;
$pid = $post->ID;
$terms = wp_get_post_terms($pid,'ad_location');
foreach($terms as $term)
{
echo $term->name." ";
}
$location = get_post_meta($pid, "Location", true);
echo $location;
?>");
</script>
Did I missed anything for the scripts? I didn't add API on it, but the console said "You have included the Google Maps API multiple times on this page. This may cause unexpected errors."
You need to make sure the map variable is initialized before you pass it to markerOptions.
A bit of overzealous debugging showed me that on the times that the page fails, the map is still undefined.
The $(document).ready() will usually occur before body.onload, so either put a call to initialize() at the very top of your $(document).ready(function() { ... }); or put the code for initialize in there.
Also, though not strictly necessary, you should consider encapsulating your map variable instead of using a global.
I'm using random user generator to get the JSON data:
http://randomuser.me/
I make a call everytime I click a button, so the zip code I get in return I use it to do a geocoder in google maps API and get a latitude and longitude. Until that it has work very well but I don't know how to use it on Google Maps. I'm trying to create D3 circles and there are two ways to do this:
1.- Using the drawing shapes from Google Maps API:
https://developers.google.com/maps/documentation/javascript/shapes#circles
2.- Using the custom overlay from Google Maps API:
https://developers.google.com/maps/documentation/javascript/customoverlays
I need to do it with the overlay and draw the graphics with D3 like in this example:
http://bl.ocks.org/mbostock/899711
So my doubts are:
1.- How can I use D3 to use the latitude and longitude and load them? In the example they load JSON from the directory but here I'm using remote data. Should I considered a JSON parse or a String or any other?
2.- What is the correct way to write this as a clean code? And why?
Thank you in advance
index.html
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css"/>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/d3.v3.js"></script>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?v&sensor=false">
</script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(16.4706001, -33.6728973),
zoom:3,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
<div id="button">
<button id="loadbutton">Click to Load</button>
</div>
<script type="text/javascript" src="js/script.js"></script>
</body>
</html>
script.js
var randomuserURL = 'http://api.randomuser.me/';
var myButton = document.getElementById('loadbutton');
myButton.onclick = loadAJAX;
var lat = '';
var lng = '';
var zipcode;
var geocoder = new google.maps.Geocoder();
function loadAJAX () {
$.ajax({
url: randomuserURL,
dataType: 'json',
success: function(data){
zipcode = data.results[0].user.location.zip;
latlng();
}
});
}
function latlng () {
geocoder.geocode( { 'address': zipcode}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
lat = results[0].geometry.location.lat();
lng = results[0].geometry.location.lng();
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
console.log('Latitude: ' + lat + ' Logitude: ' + lng);
}
You basically have everything you need.
There's no need to load a "local" file -- d3.json will take any URL as its first argument. The only problem you may run into are browser security restrictions. In that case JSONP may help.
If your code works for you, it should be fine. Honestly, you have so little code that it really doesn't matter.
I am working on a migration project from google maps V2 to V3 and wrote the bellow code but
getting error and unable to solve the problem.
Am i using wrong method of google maps?
What is wrong in this code?
<div id="map_canvas" style="width: 300px; height: 225px; font-family:arial; font-size:10px;"></div>
<?php
$map = getMap();
echo $map = str_replace('$_ADDRESS', 'MYADDRESS', $map );
function getMap()
{
$mapKey = 'MYKEY';
$_script = '
<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?key='. $mapKey .'&sensor=false"></script>
<script type="text/javascript">
//<![CDATA[
var map = null;
var geocoder = null;
// call initialize function
initialize( $_ADDRESS );
// initialize map
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
});
geocoder = new google.maps.Geocoder();
// call show Address
showAddress( address );
}
// show address
function showAddress(address)
{
if (geocoder)
{
geocoder.getPosition( address, function(point)
{
if (!point)
{
alert(address + " not found");
}
else
{
map.setCenter(point, 13);
var marker = new google.maps.Marker(point);
map.addOverlay(marker);
//marker.openInfoWindowHtml(address);
}
});
}
}
//]]>
</script>';
return $_script;
}
?>
Any idesa?
Thanks
I have split these answers as the first deals with the fundamentals of the javascript, this then deals with using the Google Maps API.
As I've never used the maps API, I can't comment on V2, but looking at how you do things in V3, I think this does what you're looking for...
<div id="map_canvas" style="width: 300px; height: 225px; font-family:arial; font-size:10px;"></div>
<?php
$map = getMap();
echo $map = str_replace('$_ADDRESS', 'MYADDRESS', $map );
function getMap()
{
$mapKey = 'MYKEY';
$_script = '
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">
//<![CDATA[
var map = null;
var geocoder = null;
// call initialize function
initialize( "$_ADDRESS" );
// initialize map
function initialize( address )
{
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
});
geocoder = new google.maps.Geocoder();
// call show Address
showAddress( address );
}
// show address
function showAddress(address)
{
if (geocoder)
{
geocoder.geocode( { "address": address }, function( results, status )
{
if ( status == google.maps.GeocoderStatus.OK )
{
position = results[0].geometry.location;
map.setCenter(position, 13);
var marker = new google.maps.Marker({ map: map, position: position });
}
else
{
alert(address + " not found");
}
});
}
}
//]]>
</script>';
return $_script;
}
?>
Having said that, I'd question the str_replace straight into the javascript - can you trust the source of that data? If not, then you should look up how to sanitise that string before you put it into your javascript or you may allow people to inject code into your site.
Looking at the fundamental javascript issues you have...
Try adding quotes around the string that you're replacing into the javascript
echo $map = str_replace('$_ADDRESS', 'MYADDRESS', $map );
Becomes:
echo $map = str_replace('$_ADDRESS', "'MYADDRESS'", $map );
That way the string that contains the address in javascript is properly quoted.
Also, ensure that you can receive the address in your initialize function:
function initialize()
Becomes:
function initialize( address )
Finally, do not redeclare "map" when you assign it a value in "initialize", otherwise you are referencing a different variable that only exists in that function:
var map = new google.maps.Map(document.getElementById("map_canvas"), {
Becomes:
map = new google.maps.Map(document.getElementById("map_canvas"), {
I'm tryng to do a map with google maps api and jquery-mobile, the map I want to do it's a directions map. I've two GPS coordinate and I wanto to show the way betwen the two points when the map is initialized. This is the code:
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="../js/jquery.ui.map.js"></script>
<script type="text/javascript" src="../js/jquery.ui.map.extensions.js"></script>
and the code of the script is:
<script type="text/javascript" >
var dirService;
var render;
function calcolateRoute(){
dirService = new google.maps.directionService();
var myOrigin = new google.maps.LatLng( 46.448327,12.37707);
var myDestination = new google.maps.LatLng( 46.443993,12.388498)
var mapOptions = {
zoom:7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: myOrigin};
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var renderOpt = { map:map };
render = new google.maps.directionRenderer(renderOpt);
var requestRoute = {
origin: myOrigin,
destination: myDestination,
travelMode: google.maps.travelMode.BICYCLING};
dirService.route(requestRoute, function(result, status){
if(status == google.maps.DirectionsStatus.OK){
render.setDirection(result);
}else{
alert('ERROR ');}
});
}
</script>
When the browser render the page i receive this error:
Uncaught TypeError: undefined is not a function
at the line
dirService = new google.maps.directionService();
I don't understand why the script return the error.... Someone can help me?
Sorry for my bad english!!
You are spelling the DirectionsService incorrectly
Should be:
dirService = new google.maps.directionsService();
Not:
dirService = new google.maps.directionService();