google map marker not defined wordpress - wordpress

I am using the code below in the Ultimatum WordPress theme template along with some PHP code to provide the dynamic values required for the map. I am getting a marker not defined error. The code is placed 3/4 of the page down within div tags, rather than in the header or footer because it is only used on the one page. I've tried a couple of suggestions I found with no luck.
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
//<![CDATA[
var geocoder;
var map;
function initialize ()
{
geocoder = new google.maps.Geocoder();
var address = document.getElementById('Property').value;
var city = document.getElementById('City').value;
var postal_code = document.getElementById('PostalCode').value;
var address_google_map = address + ', ' + city + ', ON ' + postal_code;
var myOptions =
{
zoom: 15,
mapTypeControl: true,
zoomControl: true,
zoomControlOptions:
{
style: google.maps.ZoomControlStyle.SMALL
},
StreetViewControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var info_text = address + '<br />' + city + ' ON';
var info_window = new google.maps.InfoWindow
({
content: info_text
});
var map = new google.maps.Map(document.getElementById('google_map'), myOptions);
geocoder.geocode( { 'address': address_google_map}, 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.addListener(marker, 'click', function()
{
info_window.open(map, marker);
});
}
window.onload = function() {
initialize();
}
//]]>
</script>

The marker is local to the Geocoder callback routine. Move the click listener definition inside the function where it is in scope.
geocoder.geocode( { 'address': address_google_map}, 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
});
google.maps.event.addListener(marker, 'click', function()
{
info_window.open(map, marker);
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}

Related

Remove Bounds icon on google maps marker

currently I created pages with google maps api v3, and there is a marker that user can drag. after dragend, the script with draw blue line on the road between marker. my problem is shown 2 marker on destination (a marker and "B" marker)
I've try using fitbounds() but still facing my problem.
<div id="current"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=xxx"></script>
<script type="text/javascript">
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var myOptions = {
zoom: 14,
center: new google.maps.LatLng(-7.760722, 110.408761),
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(-7.760722, 110.408761),
map: map,
draggable:true
});
google.maps.event.addListener(
marker,
'dragend',
function() {
console.log(marker.position.lat());
console.log(marker.position.lng());
var msv = new google.maps.LatLng(-7.760722, 110.408761);
var mgw = new google.maps.LatLng(marker.position.lat(), marker.position.lng());
var request = {
origin: msv,
destination: mgw,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK)
{
directionsDisplay.setDirections(response);
directionsDisplay.setMap(map);
}
else
{
alert("Directions Request from " + start.toUrlValue(6) + " to " + end.toUrlValue(6) + " failed: " + status);
}
});
}
);
how to remove bound marker ("B" marker) on destination? I expect there is only one marker in destination
You need to remove all the markers (with the {suppressMarkers:true} option on the DirectionsRenderer (they can't be suppressed separately)
var directionsDisplay = new google.maps.DirectionsRenderer({
suppressMarkers: true
});
To make the "A" Marker appear, create it:
var markerA = new google.maps.Marker({
map: map,
position: msv,
label: {
text: "A",
color: "white"
}
})
proof of concept fiddle
code snippet:
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer({
suppressMarkers: true
});
var myOptions = {
zoom: 14,
center: new google.maps.LatLng(-7.760722, 110.408761),
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(-7.760722, 110.408761),
map: map,
draggable: true
});
google.maps.event.addListener(
marker,
'dragend',
function() {
console.log(marker.position.lat());
console.log(marker.position.lng());
var msv = new google.maps.LatLng(-7.760722, 110.408761);
var mgw = new google.maps.LatLng(marker.position.lat(), marker.position.lng());
// add "A" marker
var markerA = new google.maps.Marker({
map: map,
position: msv,
label: {
text: "A",
color: "white"
}
})
var request = {
origin: msv,
destination: mgw,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
directionsDisplay.setMap(map);
} else {
alert("Directions Request from " + start.toUrlValue(6) + " to " + end.toUrlValue(6) + " failed: " + status);
}
});
}
);
html,
body,
#map_canvas {
height: 100%;
margin: 0;
padding: 0;
}
<div id="current"></div>
<div id="map_canvas"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>

Geocode was not successful for the following reason: REQUEST_DENIED in the Google Map Integration

We have integrated google location map in our wordpress website, but now when I load that page it is showing error
Geocode was not successful for the following reason: REQUEST_DENIED
When the map it is showing faded color map, For development purpose only.
My code is showing below.
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script type="text/javascript"> var geocoder, map; function mapInit(address) { 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'), mapOptions); codeAddress(address); } 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);
} }); } $(function(){ mapInit($('.current-contact .address b').html());
$('.location').click(function() {
var $this = $(this),
currentAddr = $('.current-contact').html(),
nextAddr = $this.html(),
address = $this.find('.address b').html();
codeAddress(address);
$('.current-contact').html(nextAddr);
//$this.html(currentAddr); }); });
</script>
When I get the api code, what are the changes that I need to make in this script?

Implementing google place autocomplete

This is my code for places autocomplete and search.
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places">
</script>
<script>
var geocoder;
var map;
function initialize() {
var input = document.getElementById('address');
var options = {
componentRestrictions: {country: "in"}
};
var autocomplete = new google.maps.places.Autocomplete(input,options);
geocoder = new google.maps.Geocoder();
//var latlng = new google.maps.LatLng(18.52043030000, 73.85674369999);
var mapOptions = {
zoom: 15,
//center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
map = new google.maps.Map(document.getElementById('googleMap'), mapOptions);
}
function codeAddress() {
var address = document.getElementById('address').value;
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>
This is my html code.
<input id="address" type="textbox" size="30">
<input type="button" value="Search" onclick="codeAddress()">
It is working fine but I dont want to user to click the button. When suggestions appeared, and when user select any of suggestion options, map will have to navigate to that place. How do I do this???
When User select any option from dropdown, map should navigate to that place.
Take a look at this example and the implementation of the place_changed event.
var place = autocomplete.getPlace();
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
}
This way you can pan the map to the location of the autocomplete result.
This is my working code..
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places">
</script>
<script>
var geocoder;
var map;
function initialize() {
var input = document.getElementById('address');
var options = {
componentRestrictions: {country: "in"}
};
var autocomplete = new google.maps.places.Autocomplete(input,options);
geocoder = new google.maps.Geocoder();
//var latlng = new google.maps.LatLng(18.52043030000, 73.85674369999);
var mapOptions = {
zoom: 15,
//center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
map = new google.maps.Map(document.getElementById('googleMap'), mapOptions);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
return;
}
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
marker.setIcon(/** #type {google.maps.Icon} */({
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(35, 35)
}));
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
infowindow.open(map, marker);
});
}
function codeAddress() {
var address = document.getElementById('address').value;
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>
Now user can select option from dropdown and map will navigate to that place. And also on search button click.
Hope this might help you
function initialize(){
var mapOptions = {//Map Properties
zoom:12,
center: Bangalore
};
googleMap = new google.maps.Map(document.getElementById('map-holder'),mapOptions);//map-holder is a div which holds map in my html
var defaultBounds = new google.maps.LatLngBounds(//bounds for Bengaluru
new google.maps.LatLng(12.7342888,77.3791981),
new google.maps.LatLng(13.173706,77.8826809)
);
googleMap.fitBounds(defaultBounds);
var input = (document.getElementById('searchInput'));//search input element
googleMap.controls[google.maps.ControlPosition.TOP_LEFT].push(input);//binding it to map
var searchBox = new google.maps.places.SearchBox((input));
google.maps.event.addListener(searchBox, 'places_changed', function() {//triggers when search is performed
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
var bounds = new google.maps.LatLngBounds();
for (var i = 0, place; place = places[i]; i++) {
bounds.extend(place.geometry.location);
//googleMap.fitBounds(place.geometry.viewport);
}
googleMap.fitBounds(bounds);
});
google.maps.event.addListener(googleMap, 'bounds_changed', function() {
var bounds = googleMap.getBounds();
searchBox.setBounds(bounds);
})
}

Google maps API v3 initialize function

I'd like to lean up my initialize() function... but every time I do, it breaks my code.
I'm eventually trying to do something like this, where I have a sidebar with stuff that's directly related to the markers on the map, AJAX'd in... Firstly, I'd like to be able to put other functions outside of the initialize() function. This works fine:
<script>
function initialize() {
// create the map object
var mapOptions = {
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
// create your location marker
var mylocOptions = {
draggable: true,
animation: google.maps.Animation.DROP,
icon: new google.maps.MarkerImage('//maps.gstatic.com/mapfiles/mobile/mobileimgs2.png',
new google.maps.Size(22,22),
new google.maps.Point(0,18),
new google.maps.Point(11,11)),
title: "You are here..."
};
var myloc = new google.maps.Marker(mylocOptions);
// get location information from browser, or from user input, or from database
<% if !signed_in? || !current_user.loc %>
if (navigator.geolocation) navigator.geolocation.getCurrentPosition(function(pos) {
var me = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
myloc.setPosition(me);
myloc.setMap(map);
map.setCenter(me);
$.ajax({
data: { me: me.toString() },
type: 'POST',
url: '/set-location'
})
}, function(error) {
var address = prompt('Where are you looking?');
geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var me = results[0].geometry.location
myloc.setPosition(me);
myloc.setMap(map);
map.setCenter(me);
} else {
alert("Geocode was not successful for the following reason: " + status);
};
});
});
<% else %>
var me = new google.maps.LatLng(<%= current_user.loc %>);
myloc.setPosition(me);
myloc.setMap(map);
map.setCenter(me);
map.setZoom(12);
<% end %>
// watch for marker movement, and update location accordingly
var oldPos = myloc.getPosition();
google.maps.event.addListener(myloc, "dragend", function(e){
revGeo = new google.maps.Geocoder();
var newPos = myloc.getPosition();
$.ajax({
data: { me: newPos.toString() },
type: 'GET',
url: '/set-location'
})
if(oldPos != newPos)
revGeo.geocode({'latLng': newPos}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
$('#loc').html(results[1].formatted_address);
}
} else {
alert("Geocoder failed due to: " + status);
}
});
oldPos = newPos;
});
// when creating an event, check for event location,
// verify it's existance and put a marker down on the map
$(document).on('focusout', '#event_location', function() {
geocoder = new google.maps.Geocoder();
address = document.getElementById("event_location").value;
geocoder.geocode({ 'address': address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var coords = results[0].geometry.location;
map.setCenter(coords);
var marker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: coords
});
$('#coords').html('coordinates: ' + coords)
$('#event_geocode').val(coords.toString())
} else {
alert(status + " for " + address);
};
});
});
}
</script>
... but I'm sure it can be broken up. Any ideas of what I'm doing wrong?

Google Maps API geocode function problem

Ok, I'm fooling around with Google Maps API v3 and I bumped into a problem. I don't know if its the API or just some JS error i made.
Problem:
addMarkerFromAdress() function calls on geocodeFromAdress() which returns coordinates back to addMarkerFromAdress(). But returned value is "undefined".
As a debug i added two alert outputs, one in addMarkerFromAdress() and one in geocodeFromAdress(). What troubles me is that the alert() in addMarkerFromAdress() seems to fire off before any value is returned. Why?
Source:
<script type="text/javascript">
var geocoder;
var map;
function initializeGoogleMaps() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(0, 0);
var myOptions = {
zoom: 1,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
function geocodeFromAdress(address) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latLng = results[0].geometry.location;
alert(latLng); //Outputs coordinates, but is for some reason outputted 2nd
return latLng;
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function addMarkerFromAdress(address, title){
var latLng = geocodeFromAdress(address);
alert(latLng); //Outputs "undefined", but is for some reason outputted 1st
map.setCenter(latLng);
var marker = new google.maps.Marker({
map: map,
position: latLng
});
}
window.onload = function () {
initializeGoogleMaps();
addMarkerFromAdress('Berlin, Germany', 'Berlin');
}
</script>
See that function passed as the second argument to geocoder.geocode()? that is where you should be calling addMarkerFromAddress. Due to the asynchronous nature of the geocode request, the alert after var latLng = geocodeFromAdress(address); is firing before the response is returned with the lat long values.
Something like this should do it
<script type="text/javascript">
var geocoder;
var map;
function initializeGoogleMaps() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(0, 0);
var myOptions = {
zoom: 1,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
function geocodeFromAdress(address, title) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latLng = results[0].geometry.location;
addMarkerFromAdress(latLng, title);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function addMarkerFromAdress(latLng, title){
map.setCenter(latLng);
var marker = new google.maps.Marker({
map: map,
position: latLng
});
}
window.onload = function () {
initializeGoogleMaps();
geocodeFromAdress('Berlin, Germany', 'Berlin');
}
</script>

Resources