Error with "new google.maps.directionService()" on google maps api - javascript

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();

Related

pass data from jQuery ajax GET request to google maps script

I have created an API that returns a json consisting of a latitude and longitude, and wanted to pass that into the Google Maps API, to get the corresponding map.
To get the data from my API I created an ajax request as follows:
scripts.js:
$(document).ready(function(){
$("button").click(function(){
$.get("my url", function(data, status){
//do something with this data
});
});
});
After I get the JSON from this, I want to pass the latitude and longitude to the script that Google Maps API provides as follows, inside my index.html.
index.html
<body>
<h1> JOS Map App </h1>
<button>Send an HTTP GET request to a page and get the result back</button>
<script type="text/javascript" src = "js/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src = "js/scripts.js"></script>
<div id="map"></div>
<script> //THIS ONE!!
function initMap() {
var uluru = {lat: , lng: };
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
</body>
Basically, I want to be able to pass the latitude and longitude from my GET request to this script so that I can pass them into the google maps API call. I am fairly new to jQuery, so have no idea how to do this.
Thanks!
Why not just pass the lat/lng as parameters to the Google Maps init()?
<script>
$(document).ready(function(){
$("button").click(function(){
$.get("my url", function(data, status){
initMap(data.lat, data.lng);
});
});
});
function initMap(lat, lng) {
var uluru = {lat: lat, lng: lng};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
}
</script>
You can move that initMap() function to scripts.js. Just make sure you're loading Google Maps API before your scripts.js.

How to specify location in google map?

I want to specify location in google map, I have javascript codes work fine but I do know how I can specify location from php variable
Below are sample codes.
<html>
<head>
<title></title>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCqgya6hvq6zu3Z2xeT5xEGPPi5pY2ize4&callback=initMap"></script>
</head>
<body>
<?php
//I want to search this location in google map
$location="Kigali Rwanda";
?>
<script>
var myMap;
var myLatlng = new google.maps.LatLng(52.518903284520796,-1.450427753967233);
function initialize() {
var mapOptions = {
zoom: 13,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP ,
scrollwheel: false
}
myMap = new google.maps.Map(document.getElementById('map'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: myMap,
title: 'Name Of Business',
icon: 'http://www.google.com/intl/en_us/mapfiles/ms/micons/red-dot.png'
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<div id="map" style="width:500px; height: 500px;">
</div>
</body>
</html>
Please anyone can help me
You can use Geocoding service in this case
function initMap() {
//var address = '<?php echo $location ?>';
var address = 'Kigali Rwanda';
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8
});
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': address
},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
new google.maps.Marker({
position: results[0].geometry.location,
map: map
});
map.setCenter(results[0].geometry.location);
}
});
}
#map {
height: 400px;
width: 100%;
}
<h3>My Google Maps Demo</h3>
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap">
</script>
you have to use lat, lng to specifiy location. In case of country or state name you should get lat, lng of the location and define it in the code. insert the value of php variable in hidden input field. On running script get the value and process it.

Google Maps API requires refresh to work correctly

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.

Google map v2 to v3 code

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"), {

Google Maps with Geocode returning null

I'm using Google Maps to place markers from an array of zip codes but it only places about 10% of them. The rest return null results. I can't find the problem. Here is my code.
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&language=en"></script>
<script type="text/javascript">
var latlng = new google.maps.LatLng(37.09024, -95.712891);
var map = new google.maps.Map(document.getElementById('pledge-map'), {
zoom: 4,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var geocoder = new google.maps.Geocoder();
var locations = <?php echo(json_encode($zips)); ?>
for (var i = 0; i < locations.length; i++) {
geocoder.geocode( { 'address': locations[i]}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map
});
}
});
}
</script>
locations is an array of zip code:
locations =["20190","22192","20148","06078","95136","84120","53066","53404","48323","52404","72762","89701","39667","78073","78016","76013","15613","84010","77662","77407","30127","94566","14625","45629","27406","27289","02339","01864","39116","77079","10954","37683","72801","19341","14580","64133","29579","08527","32258","33433","60093","76691","78261","77095","19426","10469","92038","85208","67220","61031","85706","72223","21222","66224","34242","30224","56232","32746","08558","72712","14209","43015","52722","32779","33518","33578","60565","11239","17007","60623","77469","20165","20002","36116","20769","20815","34209","02301","60025","48158","38804","30736","01803","45040","48069","07463","53018","73008","80951","70785","72065","91510","91506","67209","22408","36849"]
The geocoder is subject to a quota and rate limits. you are not checking for the error case (there is no code if the status returned is not OK).
Either:
look for the quota exceeded error code and handle it intelligently (add a delay and retry, only add the marker if it succeeds)
geocode the zipcodes offline and store the coordinates, use those to display your markers.

Categories