Google Maps Api Click to Map Point Add - php

How do I add point when I click on google map?
So when I click on the map I want to add a pointer but I can not.
In this process, I take a LAT LANG value from the map and transfer it into an input. Then I fill out the required fields and fill out the form. But when I click on the map, it does not put a pointer.
JSFiddle: https://jsfiddle.net/Lzycb8c0/6/
JS Code:
var lat = 41.013995; //default latitude
var lng = 28.979741; //default longitude
var homeLatlng = new google.maps.LatLng(lat, lng); //set default coordinates
var homeMarker = new google.maps.Marker({ //set marker
position: homeLatlng, //set marker position equal to the default coordinates
map: map, //set map to be used by the marker
draggable: true //make the marker draggable
});
var geocoder = new google.maps.Geocoder;
var myOptions = {
center: new google.maps.LatLng(41.013995, 28.979741), //set map center
zoom: 17, //set zoom level to 17
mapTypeId: google.maps.MapTypeId.ROADMAP //set map type to road map
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions); //initialize the map
var marker = new google.maps.Marker({
draggable: true,
position: homeLatlng,
map: map,
title: "Your location"
});
google.maps.event.addListener(map, 'click', function (event) {
document.getElementById("lat").value = event.latLng.lat();
document.getElementById("long").value = event.latLng.lng();
// Reverse geo code using latLng
geocoder.geocode({'location': event.latLng }, function(results, status) {
if (status === 'OK') {
if (results[0]) {
$('#search_new_places').val( results[0].formatted_address );
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
});
//if the position of the marker changes set latitude and longitude to
//current position of the marker
google.maps.event.addListener(homeMarker, 'position_changed', function(){
var lat = homeMarker.getPosition().lat(); //set lat current latitude where the marker is plotted
var lng = homeMarker.getPosition().lng(); //set lat current longitude where the marker is plotted
});
//if the center of the map has changed
google.maps.event.addListener(map, 'center_changed', function(){
var lat = homeMarker.getPosition().lat(); //set lat to current latitude where the marker is plotted
var lng = homeMarker.getPosition().lng(); //set lng current latitude where the marker is plotted
draggable: true;
});
var input = document.getElementById('search_new_places'); //get element to use as input for autocomplete
var autocomplete = new google.maps.places.Autocomplete(input); //set it as the input for autocomplete
autocomplete.bindTo('bounds', map); //bias the results to the maps viewport
//executed when a place is selected from the search field
google.maps.event.addListener(autocomplete, 'place_changed', function(){
//get information about the selected place in the autocomplete text field
var place = autocomplete.getPlace();
if (place.geometry.viewport){ //for places within the default view port (continents, countries)
map.fitBounds(place.geometry.viewport); //set map center to the coordinates of the location
} else { //for places that are not on the default view port (cities, streets)
map.setCenter(place.geometry.location); //set map center to the coordinates of the location
map.setZoom(17); //set a custom zoom level of 17
}
homeMarker.setMap(map); //set the map to be used by the marker
homeMarker.setPosition(place.geometry.location); //plot marker into the coordinates of the location
});
$('#plot_marker').click(function(e){ //used for plotting the marker into the map if it doesn't exist already
e.preventDefault();
homeMarker.setMap(map); //set the map to be used by marker
homeMarker.setPosition(map.getCenter()); //set position of marker equal to the current center of the map
map.setZoom(17);
$('input[type=text], input[type=hidden]').val('');
});
$('#search_ex_places').blur(function(){//once the user has selected an existing place
var place = $(this).val();
//initialize values
var exists = 0;
var lat = 0;
var lng = 0;
$('#saved_places option').each(function(index){ //loop through the save places
var cur_place = $(this).data('place'); //current place description
//if current place in the loop is equal to the selected place
//then set the information to their respected fields
if(cur_place == place){
exists = 1;
$('#place_id').val($(this).data('id'));
lat = $(this).data('lat');
lng = $(this).data('lng');
$('#n_place').val($(this).data('place'));
$('#n_description').val($(this).data('description'));
$('#search_new_places').val($(this).data('kayitliyer'));
$('#n_yetkiliad').val($(this).data('yetkiliad'));
$('#n_magazaad').val($(this).data('magazaad'));
$('#n_telefon').val($(this).data('telefon'));
$('#y_telefon').val($(this).data('yetkilitelefon'));
$('#derece').val($(this).data('derece'));
}
});
if(exists == 0){//if the place doesn't exist then empty all the text fields and hidden fields
$('input[type=text], input[type=hidden]').val('');
}else{
//set the coordinates of the selected place
var position = new google.maps.LatLng(lat, lng);
//set marker position
homeMarker.setMap(map);
homeMarker.setPosition(position);
//set the center of the map
map.setCenter(homeMarker.getPosition());
map.setZoom(17);
}
});
});

You should add a create marker in your click listener
google.maps.event.addListener(map, 'click', function (event) {
document.getElementById("lat").value = event.latLng.lat();
document.getElementById("long").value = event.latLng.lng();
var newMarker = new google.maps.Marker({
draggable: true,
position: new google.maps.LatLng(event.latLng.lat(), event.latLng.lng()),
map: map,
title: "Your location"
});
// Reverse geo code using latLng
geocoder.geocode({'location': event.latLng }, function(results, status) {
if (status === 'OK') {
if (results[0]) {
$('#search_new_places').val( results[0].formatted_address );
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
});

Related

Marker Cluster for data from MYSQL DB - Google Maps API

I have tried implementing a marker cluster into my code from the Google Developers Documentation but no joy so far. https://developers.google.com/maps/documentation/javascript/marker-clustering
Here is the snippet of code from my .JS file paying attention to the function showAllCustomers(allData) where I want to implement the Marker Clusterer:
var map;
var geocoder;
//Code to load the map with center point of Monterey MA
function initMap() {
var monterey = {lat: 42.181613, lng: -73.215013};
map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: monterey,
mapTypeId: google.maps.MapTypeId.HYBRID,
labels: true,
});
//collect customer data and geocoder object - declare geocoder as global
var cusdata = JSON.parse(document.getElementById('data').innerHTML);
geocoder = new google.maps.Geocoder();
codeAddress(cusdata);
var allData = JSON.parse(document.getElementById('allData').innerHTML);
showAllCustomers(allData)
var searchData = JSON.parse(document.getElementById('searchData').innerHTML);
showSearchedCustomer(searchData)
}
function showAllCustomers(allData) {
//declare info window variable outside of loop to allow to clear when selecting other markers
var infoWind = new google.maps.InfoWindow;
Array.prototype.forEach.call(allData, function(data){
var content = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = [data.lastName + ' ' + data.physicalAddress];
content.appendChild(strong);
//add image to infowindow - you are also able to add image path to mysql and then append dynamically
var img = document.createElement('img');
img.src = 'images/santahat.png';
img.style.width = '50px';
content.appendChild(img);
//Create markers for customer locations and customize
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.latitude, data.longitude),
map: map,
icon: iconBase + 'homegardenbusiness.png'
});
// Add event listener to open info window and show customer name
marker.addListener('mouseover', function(){
infoWind.setContent(content);
infoWind.open(map, marker);
//add event listener to zoom in to clicked customer
google.maps.event.addListener(marker, 'click', function() {
map.panTo(this.getPosition());
map.setZoom(20);
});
});
})
}
Here is my attempt to add the MarkerClusterer (code same as previous up to this point):
//Create markers for customer locations and customize
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.latitude, data.longitude),
map: map,
icon: iconBase + 'homegardenbusiness.png'
});
//create marker clusterer to group data
var markerCluster = new MarkerClusterer(map, [], {
imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
});
// Add event listener to open info window and show customer name
marker.addListener('mouseover', function(){
infoWind.setContent(content);
infoWind.open(map, marker);
//add event listener to zoom in to clicked customer
google.maps.event.addListener(marker, 'click', function() {
map.panTo(this.getPosition());
map.setZoom(20);
});
});
markerCluster.addMarker(marker);
})
}
Functioning JS file:
var map;
var geocoder;
//Code to load the map with center point of Monterey MA
function initMap() {
var monterey = {lat: 42.181613, lng: -73.215013};
map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: monterey,
mapTypeId: google.maps.MapTypeId.HYBRID,
labels: true,
});
//collect customer data and geocoder object - declare geocoder as global
var cusdata = JSON.parse(document.getElementById('data').innerHTML);
geocoder = new google.maps.Geocoder();
codeAddress(cusdata);
var allData = JSON.parse(document.getElementById('allData').innerHTML);
showAllCustomers(allData);
var searchData = JSON.parse(document.getElementById('searchData').innerHTML);
showSearchedCustomer(searchData)
}
function showAllCustomers(allData) {
//declare info window variable outside of loop to allow to clear when selecting other markers
var infoWind = new google.maps.InfoWindow;
//Create marker clusterer to group data
var markerCluster = new MarkerClusterer(map, [], {
imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
});
Array.prototype.forEach.call(allData, function(data){
var content = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = [data.lastName + ' ' + data.physicalAddress];
content.appendChild(strong);
//add image to infowindow - you are also able to add image path to mysql and then append dynamically
var img = document.createElement('img');
img.src = 'images/santahat.png';
img.style.width = '50px';
content.appendChild(img);
//Create markers for customer locations and customize
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.latitude, data.longitude),
map: map,
icon: iconBase + 'homegardenbusiness.png'
});
markerCluster.addMarker(marker);
// Add event listener to open info window and show customer name
marker.addListener('mouseover', function(){
infoWind.setContent(content);
infoWind.open(map, marker);
//add event listener to zoom in to clicked customer
google.maps.event.addListener(marker, 'click', function() {
map.panTo(this.getPosition());
map.setZoom(20);
});
});
})
}
//google maps geocoding code for address to collect lat lng from customer addresses
function codeAddress(cusdata) {
Array.prototype.forEach.call(cusdata, function(data){
var address = data.lastName + ' ' + data.physicalAddress;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == 'OK') {
map.setCenter(results[0].geometry.location);
//create object that collects the lat and lng data and pass function to update customers lat lng
var points = {};
points.id = data.id;
points.latitude = map.getCenter().lat();
points.longitude = map.getCenter().lng();
updateCustomersWithLatLng(points);
//add code to check the result status from geocode request and if we get an OVER_QUERY_LIMIT error we try again after slight delay // Jay 20201208-1015
} else if (status === google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
setTimeout(function() {
codeAddress(cusdata);
}, 100);
} // else {
// alert("Geocode was not successful for the following reason:"
// + status);
// }
});
});
}
//create update customers function that updates db using ajax call
function updateCustomersWithLatLng(points) {
$.ajax({
url:"action.php",
method:"post",
data: points,
success: function(res) {
console.log(res)
}
})
}
//When search customers is clicked create function to zoom in to the searched customer
function showSearchedCustomer(searchData) {
// var searchedCus = { ? };
// map = new google.maps.Map(document.getElementById("map"), {
// zoom: 20,
// center: searchedCus,
// });
//declare info window vairable outside of loop to allow to clear if selecting other markers
var infoWind = new google.maps.InfoWindow;
Array.prototype.forEach.call(searchData, function(data){
var content = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = [data.lastName + ' ' + data.physicalAddress];
content.appendChild(strong);
//add image to infowindow - you are also able to add image path to mysql and then append dynamically
var img = document.createElement('img');
img.src = 'images/santahat.png';
img.style.width = '50px';
content.appendChild(img);
//Create marker for searched customer location and customize
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.latitude, data.longitude),
map: map,
icon: iconBase + 'homegardenbusiness.png'
});
// Add event listner to open info window and show customer name
marker.addListener('mouseover', function(){
infoWind.setContent(content);
infoWind.open(map, marker);
});
});
}

Obtaining places based on proximity query against zip code

I'm having difficulty figuring out how to accomplish a specific type of Google Places API request.
I have a zipcode and i want to find out if there are any hospitals within 20 miles of the zipcode
I found the following example maps code and changed the request to hospitals but that didnt perform what i wanted.
So, to summarize, i just want an api request i can convert to PHP that contains an array of available hospitals within 20 miles of a zip code else an empty array. I could also take as an output just a boolean of yes hospitals exist or false otherwise
var sydney = new google.maps.LatLng(-33.867, 151.195);
infowindow = new google.maps.InfoWindow();
map = new google.maps.Map(
document.getElementById('map'), {center: sydney, zoom: 15});
var request = {
query: 'hospitals',
fields: ['name', 'geometry'],
};
service = new google.maps.places.PlacesService(map);
service.findPlaceFromQuery(request, function(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
map.setCenter(results[0].geometry.location);
}
});
}
function createMarker(place) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
The Nearby Search or Text Search services would be more appropriate for your use case, since you want to get multiple hospitals and not just one (Find Place returns a single place only).
Try the below code sample which displays hospitals within 20 miles of Pyrmont NSW 2009. Note that location must be a LatLng object, it can't be a zip code, but with Text Search you can add it to your query. Then set the type to hospital.
var map;
var service;
function initialize() {
var pyrmont = new google.maps.LatLng(-33.8665433,151.1956316);
map = new google.maps.Map(document.getElementById('map'), {
center: pyrmont,
zoom: 13
});
var request = {
location: pyrmont,
radius: '32186',
query: '2009',
type: 'hospital'
};
service = new google.maps.places.PlacesService(map);
service.textSearch(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
createMarker(results[i]);
}
}
}
function createMarker(place) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
title: place.name
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
Hope this helps!

saving marker data into db

How to save a google maps marker data into mysql DB ? using php .
And is it possible to prevent dragging that marker out of a certain country ? or maybe validating if the data is out of the wanted country when clicking on submit for example.
Yes, no problem.
The database part, you will have to do yourself. I provide you 'ajax.php'; where you receive the POST data. All I do, is print the SQL-string.
The country is Belgium, feel free to change this (now on line 39). When ever the client drops the marker anywhere but in Belgium, the marker is sent back to the position where the client started dragging
ajax.php
<?php
if($_SERVER['REQUEST_METHOD'] === 'POST') {
$sql = "INSERT INTO markers (lat, lng) VALUES (". (float) $_POST['lat'] .", ". (float) $_POST['lng'] .");";
echo $sql;
}
?>
index.php
<div id="map-canvas"></div>
<div class="controls">
<input type="button" value="SAVE" id="save_marker">
</div>
<div id="display"></div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?libraries=geometry&sensor=false"></script>
<script>
///////////////////////
// Ajax / upload part
$(document).ready(function() {
// initialize Google Maps
initialize();
// save marker to database
$('#save_marker').click(function() {
// we read the position of the marker and send it via AJAX
var position = marker.getPosition();
$.ajax({
url: 'ajax.php',
type: 'post',
data: {
lat: position.lat(),
lng: position.lng()
},
success: function(response) {
// we print the INSERT query to #display
$('#display').html(response);
}
});
});
});
///////////////////////
//Google Maps part
var map = null;
var marker = null;
var country = 'BE'; // Belgium. Feel free to use this script on any other country
// Google Maps
function initialize() {
var startDragPosition = null;
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(50.5, 4.5), // Over Belgium
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// set the new marker
marker = new google.maps.Marker({
position: new google.maps.LatLng(50.5, 4.5),
map: map,
draggable: true
});
var myGeocoder = new google.maps.Geocoder();
// set a callback for the start and end of dragging
google.maps.event.addListener(marker,'dragstart',function(event) {
// we remember the position from which the marker started.
// If the marker is dropped in an other country, we will set the marker back to this position
startDragPosition = marker.getPosition();
});
google.maps.event.addListener(marker,'dragend',function(event) {
// now we have to see if the country is the right country.
myGeocoder.geocode({'latLng': marker.getPosition()}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK && results[1]) {
var countryMarker = addresComponent('country', results[1], true);
if (country != countryMarker) {
// we set the marker back
marker.setPosition(startDragPosition);
}
}
else {
// geocoder didn't find anything. So let's presume the position is invalid
marker.setPosition(startDragPosition);
}
});
});
}
/**
* geocodeResponse is an object full of address data.
* This function will "fish" for the right value
*
* example: type = 'postal_code' =>
* geocodeResponse.address_components[5].types[1] = 'postal_code'
* geocodeResponse.address_components[5].long_name = '1000'
*
* type = 'route' =>
* geocodeResponse.address_components[1].types[1] = 'route'
* geocodeResponse.address_components[1].long_name = 'Wetstraat'
*/
function addresComponent(type, geocodeResponse, shortName) {
for(var i=0; i < geocodeResponse.address_components.length; i++) {
for (var j=0; j < geocodeResponse.address_components[i].types.length; j++) {
if (geocodeResponse.address_components[i].types[j] == type) {
if (shortName) {
return geocodeResponse.address_components[i].short_name;
}
else {
return geocodeResponse.address_components[i].long_name;
}
}
}
}
return '';
}
</script>
<style>
#map-canvas {
height:400px;
}
</style>

Reverse Geocode On Google Maps api v3

I wonder whether someone may be able to help me please.
I using the code shown below to correctly plot markers retrieved from a MySQL database on a Google Map.
<script type="text/javascript">
//Sample code written by August Li
var icon = new google.maps.MarkerImage("images/location-marker-2.png")
new google.maps.Point(16, 32);
var center = null;
var map = null;
var bounds = new google.maps.LatLngBounds();
function addMarker(lat, lng, info) {
var pt = new google.maps.LatLng(lat, lng);
bounds.extend(pt);
var marker = new google.maps.Marker({
position: pt,
icon: icon,
map: map
});
}
function initMap() {
map = new google.maps.Map(document.getElementById("gmaps-canvas"), {
center: new google.maps.LatLng(0, 0),
zoom: 6,
scrollwheel: true,
draggable: true,
mapTypeId: google.maps.MapTypeId.SATELLITE
});
<?php
include("admin/link.php");
include("admin/opendb.php");
$query = mysql_query("SELECT * FROM `detectinglocations` WHERE `locationid` = '$lid'");
while ($row = mysql_fetch_array($query)){
$locationname=$row['locationname'];
$osgb36lat=$row['osgb36lat'];
$osgb36lon=$row['osgb36lon'];
echo ("addMarker($osgb36lat, $osgb36lon,'<b>$locationname</b><br/>');\n");
}
mysql_close($connect);
?>
center = bounds.getCenter();
map.fitBounds(bounds);
}
</script>
What I'm now trying to do is add further functionality that allows users to also click on the map to plot new markers, in essence using the pre-existing marker from the database as a point to work from, performing a reverse geocode.
I've been researching this for a number of days now and I've tried to implement a whole host of tutorials, but I just can't seem to get both parts of the functionality working.
I do know that to enable a on-click event I need to incorporate something along the lines of:
google.maps.event.addListener(map, 'click', function(event) {
marker.setPosition(event.latLng)
geocode_lookup( 'latLng', event.latLng );
});
}
but I must admit I'm a little unsure about what else I need to incorporate.
I just wondered whether someone may be able to take a look at this please, and I'd be very grateful if someone could show me where I've gone wrong.
Many thanks and kind regards
I wrote a separate maps page with just click-to-reverse-geocode functionality
http://jsfiddle.net/ZDQeM/
The address details are confusing to work with, I think. The results are an array, at different levels of precision, one might include the county, another the state, another the street address. Generally I only use results[0]. The details are in the docs: https://developers.google.com/maps/documentation/javascript/geocoding#GeocodingResponses
If you need specific information the sure way to obtain it is iterate through the whole results array until you find what you need (types[] containing postal_code, for example).
google.maps.event.addListener(map, 'click', function(event) {
userMarker = new google.maps.Marker({
map: map,
position: event.latLng
});
geocoder.geocode({'latLng': event.latLng}, function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
alert(results[0].formatted_address);
}
else {
alert("No results");
}
}
else {
alert("Geocoding unsuccessful: Status " + status);
}
});
});
Where in your code?
<script type="text/javascript">
//Sample code written by August Li
var icon = new google.maps.MarkerImage("images/location-marker-2.png")
new google.maps.Point(16, 32);
var center = null;
var map = null;
var bounds = new google.maps.LatLngBounds();
function addMarker(lat, lng, info) {
var pt = new google.maps.LatLng(lat, lng);
bounds.extend(pt);
var marker = new google.maps.Marker({
position: pt,
icon: icon,
map: map
});
}
function initMap() {
map = new google.maps.Map(document.getElementById("gmaps-canvas"), {
center: new google.maps.LatLng(0, 0),
zoom: 6,
scrollwheel: true,
draggable: true,
mapTypeId: google.maps.MapTypeId.SATELLITE
});
<?php
include("admin/link.php");
include("admin/opendb.php");
$query = mysql_query("SELECT * FROM `detectinglocations` WHERE `locationid` = '$lid'");
while ($row = mysql_fetch_array($query)){
$locationname=$row['locationname'];
$osgb36lat=$row['osgb36lat'];
$osgb36lon=$row['osgb36lon'];
echo ("addMarker($osgb36lat, $osgb36lon,'<b>$locationname</b><br/>');\n");
}
mysql_close($connect);
?>
center = bounds.getCenter();
map.fitBounds(bounds);
var geocoder = new google.maps.Geocoder();
google.maps.event.addListener(map, 'click', function(event) {
var userMarker = new google.maps.Marker({
map: map,
position: event.latLng
});
geocoder.geocode({'latLng': event.latLng}, function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
alert(results[0].formatted_address);
}
else {
alert("No results");
}
}
else {
alert("Geocoding unsuccessful: Status " + status);
}
});
});
}
</script>

Google Maps - maintain current position and zoom when reloading dynamic map pointers

I have been searching high and low for a solution to this problem. I fetch dynamic positions of markers and show the map positioned and zoomed baased on the City that has been selected in my application. If I then scroll or zooom the Google map and then request an update of the markers position (by fetching the xml) I loose the new position and zoom I was at. How do I make the function check what the current getCenter and getZoom is to use in the reload of the map ?
function load() {
if(map) { // Does not work
var lat = map.getCenter().lat();
var lng = map.getCenter().lng();
var zoom = map.getZoom();
} else {
var lat = '<?=$Lat?>';
var lng = '<?=$Lon?>';
var zoom = <?=$zoom?>;
}
var map_options = {
center: new google.maps.LatLng(lat,lng),
zoom: zoom,
mapTypeId: '<?=$map_type?>'
};
var map = new google.maps.Map(document.getElementById("map"), map_options);
var infoWindow = new google.maps.InfoWindow;
<< Other marker creating code here that works fine >>
}
remove the var? to make the lat,lng, zoom global var
if(map) { // Does not work
lat = map.getCenter().lat();
lng = map.getCenter().lng();
zoom = map.getZoom();
} else {
lat = '<?=$Lat?>';
lng = '<?=$Lon?>';
zoom = <?=$zoom?>;
}
UPDATE
move the var map outside of function load() {}
something like this:
var map, lat, lng, zoom;
function load(){...map = new google.maps.Map(document.getElementById("map"), map_options);
...}
let me explain this shortly
when page is loaded var map is initiated as "nothing/null", therefore if(map) will be false then
use the lat,lng,zoom from your PHP
after map = new
google.maps.Map(document.getElementById("map"),
map_options); , map holders the js
object of gmap.
then load(){...} is called again if(map) is true then the
block will be executed

Categories